python windows服务

来源:百度知道 编辑:UC知道 时间:2024/06/05 05:43:02
import win32serviceutil
import win32service
import win32event

class win32test(win32serviceutil.ServiceFramework):
_svc_name_ = "Python Win32 Service"
_svc_display_name_ = "Python Win32 Service"
_svc_description_ = "Just for a demo, do nothing."
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

def SvcDoRun(self):
win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)

def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)

if __name__=='__main__':
win32serviceutil.HandleCommandLine(win32test)
上面是一个服务的范例 修改哪个参数或怎么修改能让SvcDoRun运行结束后等待停止几秒后重新运行一遍

楼主怎么又来问这个问题?不是已经问过一遍了吗?这么久还没有搞定?
SvcDoRun运行结束就表示系统服务“停止”,怎么会重新运行?

上面的程序在开始添加两行代码:
import time
timeout = 10 #此处是延时时间,单位秒

改写部分代码:
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.running = True
def SvcDoRun(self):
while self.running:
#调用你的程序代码或者函数,以下的部分是计时代码
i = 0
while self.running and (i<timeout):
time.sleep(1)
i += 1
def SvcStop(self):
self.running = False
这三个函数完全替代原有的代码
代码 import win32event 可以去除

计时代码之所以不直接写 time.sleep(timeout),主要原因是当timeout比较长时,会引起停止服务时失败,windows系统在停止服务时会有一定的等待时间,但时间不长,现在的计时代码是一秒钟检查一次是否停止,肯定不会带来问题。

这个模块没用过, 不过运行结束后等待停止几秒后重新运行一遍, 这可以用time模块的sleep(time)实现(time是秒数), 你可以在他们外面用一个while 1来循环