正文
本篇文章的定时任务是运行在windows服务中的,因此我们首先需要安装pywin32模块
1.、安装pywin32
pip install pywin32
2.、服务操作相关命令
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
3.、启动服务时被拒绝
Installing service timingTaskDaemon
Error installing service: 拒绝访问。 (5)
a.大多数原因是由于python环境配置的问题,python默认安装时配置的pah是用户环境变量,这里我们需要改成系统环境变量,具体可以参考
Python 写windows service 及 start service 出现错误 1053:服务没有及时响应启动或控制请求
b.考虑命令行是否有权限,我自己的win8系统默认权限就不够,需要右键管理员启动才可以
4、 实现windows服务功能,我们需要继承win32serviceutil.ServiceFramework这个类,把需要执行的业务逻辑放入SvcDoRun函数中,如下代码中executeJob()函数即为我们定时执行的任务
class WeatherPythonService(win32serviceutil.ServiceFramework):
_svc_name_ = "weather_service_test4"
_svc_display_name_ = "weather_service_test4"
_svc_description_ = "i am a test weather_service_test"
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0