后台运行程序可以作为console app长期运行,但可能被关闭,改成服务后能避免。程序中加入了日志文件,可以记录服务运行情况。
# -*- coding: utf-8 -*-
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
import os
import traceback
import sys
import logging
import getpath
sys.path.insert(0,getpath.getpath())
from logging.handlers import RotatingFileHandler
log_filename=os.path.join(getpath.getpath(),"report.log")
handlers=[RotatingFileHandler(filename=log_filename, maxBytes=10*1024*1024, encoding='utf-8',backupCount=3)]
logging.basicConfig(level=logging.DEBUG,
format = '%(asctime)s - %(name)s - %(levelname)s -%(funcName)s - %(message)s',
handlers=handlers)
import time
import ls
import cj
def loop_one():
time_b=time.perf_counter()
ls.bjls()
ls.qdls()
ls.cdls()
cj.bjcj()
cj.qdcj()
cj.cdcj()
usetime=time.perf_counter()-time_b
logging.info(usetime)
logging.warning("长期运行,不要关闭!!!")
remain=5*60-usetime
if remain>0:
time.sleep(remain)
class MyService(win32serviceutil.ServiceFramework):
_svc_name_ = 'MyService_caiji'
_svc_display_name_ = 'MyService_caiji'
def __init__(self, args):
pass
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
socket.setdefaulttimeout(60)
self.is_alive = True
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
self.is_alive = False
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_, ''))
self.main()
def main(self):
logging.info("main")
self.is_alive = True
while self.is_alive:
loop_one()
# python my_service.py install
# python my_service.py start # 启动服务
# python my_service.py stop # 停止服务
# python my_service.py remove # 从系统中移除服务
def main():
if len(sys.argv) == 1:
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(MyService)
servicemanager.StartServiceCtrlDispatcher()
else:
win32serviceutil.HandleCommandLine(MyService)
def test():
m=MyService([])
m.main()
if __name__ == '__main__':
main()
# test()