python定时任务windows服务
一、python调用外部exe文件
import subprocess
subprocess.call('notepad')
import subprocess
#字符串中含有空格,所以有 r''
subprocess.call("D:\Program Files (x86)\Netease\CloudMusic\cloudmusic.exe")
二、定时任务
pip install py-task
from task import task
from task import task_container
from task.job import job
from task.trigger import cron_trigger
class MyJob(job.Job):
def __init__(self):
pass
def execute(self):
print 'Hello now is ' + str(time.time())
cron = '0-59/5 10,15,20 * * * * 2015'
new_task = task.Task('Task', MyJob(), cron_trigger.CronTrigger(cron))
container.add_task(new_task)
container.start_all()
三、python开发windows服务
一个简单的服务模版:
#encoding=utf-8
#ZPF
import win32serviceutil
import win32service
import win32event
class PythonService(win32serviceutil.ServiceFramework):
#服务名
_svc_name_ = "PythonService"
#服务在windows系统中显示的名称
_svc_display_name_ = "Python Service Test"
#服务的描述
_svc_description_ = "This code is a Python service Test"
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
def SvcDoRun(self):
# 把自己的代码放到这里,就OK
# 等待服务被停止
win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
def SvcStop(self):
# 先告诉SCM停止这个过程
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
# 设置事件
win32event.SetEvent(self.hWaitStop)
if __name__=='__main__':
win32serviceutil.HandleCommandLine(PythonService)
#括号里参数可以改成其他名字,但是必须与class类名一致;
服务示例:
#ZPF
#encoding=utf-8
import win32serviceutil
import win32service
import win32event
import os
import logging
import inspect
class PythonService(win32serviceutil.ServiceFramework):
_svc_name_ = "PythonService"
_svc_display_name_ = "Python Service Test"
_svc_description_ = "This is a python service test code "
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
self.logger = self._getLogger()
self.run = True
def _getLogger(self):
logger = logging.getLogger('[PythonService]')
this_file = inspect.getfile(inspect.currentframe())
dirpath = os.path.abspath(os.path.dirname(this_file))
handler = logging.FileHandler(os.path.join(dirpath, "service.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("service is run....")
while self.run:
self.logger.info("I am runing....")
time.sleep(2)
def SvcStop(self):
self.logger.info("service is stop....")
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
self.run = False
if __name__=='__main__':
if len(sys.argv) == 1:
try:
evtsrc_dll = os.path.abspath(servicemanager.__file__)
servicemanager.PrepareToHostSingle(PythonService)
servicemanager.Initialize('PythonService', evtsrc_dll)
servicemanager.StartServiceCtrlDispatcher()
except win32service.error, details:
if details[0] == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
win32serviceutil.usage()
else:
win32serviceutil.HandleCommandLine(PythonService)
四、pyinstaller 打包为控制台文件
if __name__ == '__main__':
from PyInstaller.main import run
params=['windows_services_in_python.py', '-F', '-c', '--icon=favicon.ico']
run(params)
cmd进入exe所在目录:
windows_services_in_python.exe install
windows_services_in_python.exe start
五、python操作window服务
1.安装服务
python PythonService.py install
2.让服务自动启动
python PythonService.py --startup auto install
3.启动服务
python PythonService.py start
4.重启服务
python PythonService.py restart
5.停止服务
python PythonService.py stop
6.删除/卸载服务
python PythonService.py remove
还没有评论,来说两句吧...