返回顶部

收藏

python使用win32service,apscheduler生成windows服务

更多
#-*- coding:utf-8 -*-
'''
Created on 2014年8月20日

@author: 188007
'''
import win32serviceutil 
import win32service 
import win32event 
from datetime import datetime,timedelta,date
import sys
sys.path.append("F:/workspace/itvdms")
import py_compile
py_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 = False

if __name__=='__main__': 
    win32serviceutil.HandleCommandLine(ITVDMSService)

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

from apscheduler.scheduler import Scheduler
from apscheduler.jobstores.sqlalchemy_store import SQLAlchemyJobStore

scheduler = Scheduler(daemonic=False)  #coalesce=True,daemonic=True
scheduler.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):
        pass

def shutdown():
    try:
        scheduler.shutdown()
    except (KeyboardInterrupt, SystemExit):
        pass

标签:python,win32service,apscheduler,windows

收藏

1人收藏

支持

0

反对

0

相关聚客文章
  1. admin 发表 2015-05-15 15:35:34 python与macro宏调用
  2. 博主 发表 2011-08-20 16:00:00 Windows上Python备份MySQL脚本
  3. admin 发表 2015-05-14 14:38:14 Excel vba将chart另存为图片
  4. 博主 发表 2016-09-10 00:00:00 Windows 上 Python 开发环境搭建
  5. 馒头 发表 2013-02-27 03:03:30 php 5.4 + apache 2 + xdebug 2 + Windows
  6. 博主 发表 2015-03-14 00:00:00 use python in windows
  7. -Y.c 发表 2016-05-26 16:19:52 基于Python使用Gmail通信的Windows后门:Gdog
  8. 博主 发表 2013-04-03 00:00:00 windows下安装python虚拟机环境virtualenv
  9. 博主 发表 2015-03-14 00:00:00 use python in windows
  10. 飞尘 发表 2011-12-16 13:00:00 python使用logging模块之二
  11. 博主 发表 2013-04-03 00:00:00 windows下安装python虚拟机环境virtualenv
  12. 飞尘 发表 2011-12-23 12:10:40 python安装模块报错缺少ez_setup