python程序作为window 服务运行

 后台运行程序可以作为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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值