环境
Python版本:2.7.18
apscheduler版本:3.9.1.post1(直接用pip install apscheduler安装)
发现问题
from apscheduler.schedulers.background import BackgroundScheduler
def task():
print 'test'
scheduler = BackgroundScheduler()
scheduler.add_job(task, 'cron', hour=6, minute=0)
scheduler.start()
到点执行task就GG了:
Exception in thread APScheduler:
Traceback (most recent call last):
File "D:\Python27\lib\threading.py", line 801, in __bootstrap_inner
self.run()
File "D:\Python27\lib\threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "D:\Python27\lib\site-packages\apscheduler\schedulers\blocking.py", line 32, in _main_loop
wait_seconds = self._process_jobs()
File "D:\Python27\lib\site-packages\apscheduler\schedulers\base.py", line 974, in _process_jobs
run_times = job._get_run_times(now)
File "D:\Python27\lib\site-packages\apscheduler\job.py", line 135, in _get_run_times
next_run_time = self.trigger.get_next_fire_time(next_run_time, now)
File "D:\Python27\lib\site-packages\apscheduler\triggers\cron\__init__.py", line 179, in get_next_fire_time
next_date, fieldnum = self._increment_field_value(next_date, fieldnum - 1)
File "D:\Python27\lib\site-packages\apscheduler\triggers\cron\__init__.py", line 147, in _increment_field_value
return normalize(dateval + difference), fieldnum
File "D:\Python27\lib\site-packages\apscheduler\util.py", line 431, in normalize
return datetime.fromtimestamp(dt.timestamp(), dt.tzinfo)
AttributeError: 'datetime.datetime' object has no attribute 'timestamp'
很简单,其实就是python2.7的datetime.datetime没有timestamp这个方法。也就是说这个版本的apscheduler并不适配Python2.7。
于是我就去搜了下看看Python2.7应该安装哪个版本的apscheduler,但是我没找着。
看到有个帖子也提了一样的问题,但是最后的建议竟是让改用Python3 (黑人问号)。
解决问题
行吧,没找到合适的版本库,那就自己动手,丰衣足食吧。直接改它util.py的代码,把用到timestamp的地方换了个实现去取时间戳,然后就好了。。。(出乎意料的顺利)
def normalize(dt):
# return datetime.fromtimestamp(dt.timestamp(), dt.tzinfo)
import time
return datetime.fromtimestamp(time.mktime(dt.timetuple()), dt.tzinfo)
其他问题
- 如果在定时任务执行失败了但是没看到有报错信息,只看到No handlers could be found for logger “apscheduler.executors.default”,则需要在实例化BackgroundScheduler前加上以下代码:
import logging logging.basicConfig()
- 在linux服务器中使用nohup后台运行python脚本发现log文件里也没有print输出日志,查了下发现是python输出缓冲的问题,执行时需要加上-u参数不启用才能实时在日志文件中看到print输出。
【参考链接】
[1] python 2.7 ‘datetime.datetime’ object has no attribute ‘timestamp’
[2] 【Apscheduler】不生效也不报错,提示No handlers could be found for logger “apscheduler.executors.default”
[3] Python 定时任务框架 APScheduler 详解
[4] 用nohup执行python程序时,print无法输出