2009-12-05 02:54:07
1、想寫一個監視服務器是否運行的簡單服務,網上搜到的例程不太完善,如梅勁松的許久沒有更新,而且SvcDoRun寫得不完整(見http://www.chinaunix.net/jh/55/558190.html,
不知道是不是原始出處);而mail.python.org中的沒有定義_svc_name_等變量(見
http://mail.python.org/pipermail/python-list/2005-December/315190.html)
2、這個實現功能很簡單,就是把當前時間寫入‘c:\\temp\\time.txt’文件,一看即知,大家可以隨意擴充。
3、用
service install 安裝
service start啟動
service stop停止
service debug調試
service remove刪除
service.py
---代碼開始
#coding:utf-8
import win32serviceutil
import win32service
import win32event
import win32evtlogutil
import time
class service(win32serviceutil.ServiceFramework):
_svc_name_ = "test_python"
_svc_display_name_ = "test_python"
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
print '服務開始'
def SvcDoRun(self):
import servicemanager
#------------------------------------------------------
# Make entry in the event log that this service started
#------------------------------------------------------
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,servicemanager.PYS_SERVICE_STARTED,(self._svc_name_, ''))
#-------------------------------------------------------------
# Set an amount of time to wait (in milliseconds) between runs
#-------------------------------------------------------------
self.timeout=100
while 1:
#-------------------------------------------------------
# Wait for service stop signal, if I timeout, loop again
#-------------------------------------------------------
rc=win32event.WaitForSingleObject(self.hWaitStop,self.timeout)
#
# Check to see if self.hWaitStop happened
#
if rc == win32event.WAIT_OBJECT_0:
#
# Stop signal encountered
#
break
else:
#
# Put your code here
#
#
f=open('c:\\temp\\time.txt','w',0)
f.write(time.ctime(time.time()))
f.close()
print '服務運行中'
time.sleep(1)
#
# Only return from SvcDoRun when you wish to stop
#
return
def SvcStop(self):
#---------------------------------------------------------------------
# Before we do anything, tell SCM we are starting the stop process.
#---------------------------------------------------------------------
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
#---------------------------------------------------------------------
# And set my event
#---------------------------------------------------------------------
win32event.SetEvent(self.hWaitStop)
print '服務結束'
return
if __name__=='__main__':
win32serviceutil.HandleCommandLine(service)
---代碼結束