注意要import script文件
另外script文件中的方法不要有控制台打印输出
'''
Usage : python resartHubService.py install
Usage : python resartHubService.py start
Usage : python resartHubService.py stop
Usage : python resartHubService.py remove
'''
import os
import time
import win32service
import win32serviceutil
import win32api
import win32con
import win32event
import win32evtlogutil
from restartHub import RestartHub
import servicemanager
class RestartHubService(win32serviceutil.ServiceFramework):
_svc_name_ = "RestartHubService"
_svc_display_name_ = "RestartHubService"
_svc_description_ = "RestartHubService"
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,servicemanager.PYS_SERVICE_STARTED,(self._svc_name_, ''))
self.timeout = 2000
servicemanager.LogInfoMsg("Running restart service program..")
try:
service = RestartHub()
service.restartHubMain()
except:
pass
while 1:
rc = win32event.WaitForSingleObject(self.hWaitStop, self.timeout)
# Check to see if self.hWaitStop happened
if rc == win32event.WAIT_OBJECT_0:
# Stop signal encountered
servicemanager.LogInfoMsg("The %s service has stoped." % self._svc_name_)
service.stopJob()
break
def ctrlHandler(ctrlType):
return True
if __name__ == '__main__':
win32api.SetConsoleCtrlHandler(ctrlHandler, True)
win32serviceutil.HandleCommandLine(RestartHubService)
# Done! Lets go out and get some dinner, bitches!
这里我调用的是一个Cron Job,所以没有使用while 1的loop,而是直接调用
service = RestartHub()
service.restartHubMain()
并且需要处理service stop的信号,service.stopJob()
这是job的代码:
def restartHubMain(self):
self.write(self.hostname)
self.scheduler = Scheduler(daemonic = False)
self.scheduler.start()
job = self.scheduler.add_cron_job(self.restartService,day_of_week=self.day_of_week,hour=self.hour,minute=self.minute,second=self.second)
def stopJob(self):
self.scheduler.shutdown()