Celery scheduled tasks problems with Timezone

前端 未结 3 1634
一向
一向 2021-01-12 09:20

I\'m using celery in a server where server time is now BST, and suddenly my scheduled tasks are executing one hour before! Previously, serv

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-12 09:52

    You might find it easier to set your CELERY_TIMEZONE to be 'UTC'. Then, if you want to use Local times to schedule events, you can do the following:

    london_tz = pytz.timezone('Europe/London')
    london_dt = london_tz.localize(datetime.datetime(year, month, day, hour, min))
    give_this_to_celery = london_dt.astimezone(pytz.UTC)
    

    Admittedly, this is more work. Localize a datetime, then convert it and get a naive datetime back. But it should take care of most of the headaches from working with timezones.

    Edit: you asked,

    Can you please tell me what exactly CELERY_TIMEZONE does? And how celery use eta value to calculate countdown?

    Celery allows you to defer the execution of a function call by specifying the eta parameter. eta is a datetime object that represent when you want the function to be run. CELERY_TIMEZONE specifies the timezone of the datetimes used for eta. So, if we set CELERY_TIMEZONE = 'America/New_York', all of our eta parameters will be interpreted as if they represented New York time.

    Better is to set CELERY_TIMEZONE = 'UTC', and pass datetime objects that represent UTC timestamps. This avoids a lot of the problems caused by daylight savings time.

    More information available in the docs

    Edit,

    please see clarification and corrections by asksol on how eta parameter is constructed in the comments.

提交回复
热议问题