文章目錄

Celery定时任务里介绍,配置定时任务使用crontab, 并设置timezone。于是配置了timezone=”Asia/Shanghai”, 然而时间总是偏差8个小时,在Cannot use local time for cron schedules and UTC for solar schedules里找到解决的办法。原来问题的根源是Celery里的now函数定义出错了。查看now函数的实现

1
2
3
4
def now(self):
"""Return the current time and date as a datetime."""
from datetime import datetime
return datetime.utcnow().replace(tzinfo=self.timezone)

如果写成

1
2
3
4
def now(self):
"""Return the current time and date as a datetime."""
from datetime import datetime
return datetime.now(self.timezone)

就没问题了。
查看datetime.now的实现, 当tz不为空时, datetime.now(tz) 等于tz.fromutc(datetime.utcnow().replace(tzinfo=tz))。所以这是Celery的Bug

但是不能去修改Celery的源码,于是使用评论中提到的解决办法

1
2
3
4
5
6
7
class MyCelery(Celery)
def now(self):
"""Return the current time and date as a datetime."""
from datetime import datetime
return datetime.now(self.timezone)

app = MyCelery()

打赏作者

文章目錄