首页 > 解决方案 > Celery beat_schedule 使用了错误的时区

问题描述

我正在尝试使用 celery beat 将日常任务作为我的 Django Web 应用程序的一部分运行,它调用一个带有日期字符串参数的函数。节拍时间表工作正常,并且每天在正确的时间调用该函数,但输入到该函数的日期字符串总是晚一天。我认为这是因为时区设置错误,但我认为我已经正确配置了 Django 和 celery,所以我看不出问题出在哪里。

中的相关设置./settings.py

TIME_ZONE = 'Europe/London'
USE_TZ = True
CELERY_ENABLE_UTC = False
CELERY_TIMEZONE = TIME_ZONE

我的芹菜配置./my_project/celery.py

from django.utils import timezone
from celery import Celery
from celery.schedules import crontab


app = Celery('my_project')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()

# Configure daily tasks
app.conf.beat_schedule = {
    # Executes `my_task` every day at 10:00am
    'do-my-task': {
        'task': 'tasks.tasks.my_task',
        'schedule': crontab(minute=0, hour=10),
        'args': (timezone.now().strftime('%d/%m/%Y'), ),
    },
}

有什么想法为什么应该输入错误的日期字符串作为参数my_task

标签: djangocelerycelerybeat

解决方案


django.utils.timezone.now不做你认为它做的事。 根据文档,它将返回 UTC 时间,时区设置为 UTC。它不会Europe/London按照您的意愿返回时间:

如果USE_TZTrue,这将是一个感知datetime的,以 UTC 表示当前时间。请注意,now()无论 ; 的值如何,都将始终返回 UTC 时间TIME_ZONE。您可以使用localtime()获取当前时区的时间。

正如文档建议的那样,使用localtime而不是now.


推荐阅读