python使用win32service,apscheduler生成windows服务,,#-*- coding:


#-*- coding:utf-8 -*-'''Created on 2014年8月20日@author: 188007'''import win32serviceutil import win32service import win32event from datetime import datetime,timedelta,dateimport syssys.path.append("F:/workspace/itvdms")import py_compilepy_compile.compile("F:/workspace/itvdms/task/scheduler.py")from scheduler import *'''#让服务自动启动#python ITVDMSService.py --startup auto install#删除/卸载服务#python ITVDMSService.py remove#启动服务#python ITVDMSService.py start#重启服务#python ITVDMSService.py restart#停止服务#python ITVDMSService.py stop了解 Windows 服务体系结构http://technet.microsoft.com/zh-cn/library/aa998749(EXCHG.65).aspx'''class ITVDMSService(win32serviceutil.ServiceFramework):     """    Usage: 'ITVDMSService.py [options] install|update|remove|start [...]|stop|restart [...]|debug [...]'    Options for 'install' and 'update' commands only:     --username domain\username : The Username the service is to run under     --password password : The password for the username     --startup [manual|auto|disabled|delayed] : How the service starts, default = manual     --interactive : Allow the service to interact with the desktop.     --perfmonini file: .ini file to use for registering performance monitor data     --perfmondll file: .dll file to use when querying the service for       performance data, default = perfmondata.dll    Options for 'start' and 'stop' commands only:     --wait seconds: Wait for the service to actually start or stop.                     If you specify --wait with the 'stop' option, the service                     and all dependent services will be stopped, each waiting                     the specified period.    """    #服务名    _svc_name_ = "ITVDMSService"    #服务显示名称    _svc_display_name_ = "ITView DMS Monitor"    #服务描述   描述串是Unicode编码转成UTF-8编码,所以在显示时需要解码为UTF-8编码,如此在服务中看到的才是中文    _svc_description_ = "ITVDMS销售监控系统数据抓取服务,主要功能两个。一个是每隔10分钟抓取一次销售主数据,另外一个是每日6点抓取销售基础数据。".decode("utf-8")    def __init__(self, args):         win32serviceutil.ServiceFramework.__init__(self, args)         self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)        self.logger = self._getLogger()        self.isAlive = True    def _getLogger(self):        import logging        import os        import inspect        logger = logging.getLogger('[ITVDMSService]')        this_file = inspect.getfile(inspect.currentframe())        dirpath = "D:/workspace/itvdms/logs"        #dirpath = os.path.abspath(os.path.dirname(this_file))        handler = logging.FileHandler(os.path.join(dirpath, "itvdms.log"))        formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')        handler.setFormatter(formatter)        logger.addHandler(handler)        logger.setLevel(logging.INFO)        return logger    def SvcDoRun(self):        import time        self.logger.info("itvdms start.... %s " % datetime.now())         start()        #while self.isAlive:            #self.logger.info("itvdms monitor alive. %s " % datetime.now())        #    time.sleep(1)        # 等待服务被停止         win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)    def SvcStop(self):         # 先告诉SCM停止这个过程         self.logger.info("itvdms shutdown.... %s " % datetime.now())        shutdown()        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)         # 设置事件         win32event.SetEvent(self.hWaitStop)         self.isAlive = Falseif __name__=='__main__':     win32serviceutil.HandleCommandLine(ITVDMSService)

上面class使用到的start和shutdown方法

from apscheduler.scheduler import Schedulerfrom apscheduler.jobstores.sqlalchemy_store import SQLAlchemyJobStorescheduler = Scheduler(daemonic=False)  #coalesce=True,daemonic=Truescheduler.add_listener(err_listener, EVENT_JOB_ERROR | EVENT_JOB_MISSED)sqlalchemyJobStore = SQLAlchemyJobStore(url=__MYSQL_url,engine=__engine,tablename=JOB_TABLE_NAME)scheduler.add_jobstore(sqlalchemyJobStore, DB_ENGINE)def start():    try:        scheduler.start()    except (KeyboardInterrupt, SystemExit):        passdef shutdown():    try:        scheduler.shutdown()    except (KeyboardInterrupt, SystemExit):        pass

评论关闭