Celery beat - different time zone per task

不羁岁月 提交于 2019-12-06 13:53:19

You can achieve a timezone-aware scheduling of individual tasks in a celery schedule. This way you can run a task according to the local time in a specific timezone (also adjusting to e.g. daylight saving time) by specifying a separate now function for each celery schedule

crontab supports the nowfun argument to specify the datetime function to be used to check if it should run

import datetime
import pytz
nowfun = lambda: datetime.datetime.now(pytz.timezone('Europe/Berlin'))

In your schedule, set this function as the datetime function via

'periodic_task': {
    'task': 'api.tasks.periodic',
    'schedule': crontab(hour=6, minute=30, nowfun=nowfun)
}

This runs every day at 6.30am CET adjusted to daylight savings.

In case you use the function more than once, consider creating a helper

from functools import partial
cet_crontab = partial(crontab, nowfun=nowfun)
'periodic_task': {
    'task': 'api.tasks.periodic',
    'schedule': cet_crontab(hour=6, minute=30)
}

Make sure you have CELERY_ENABLE_UTC = False set, otherwise celery converts your schedules to UTC.

I think the easiest way to do it is to use decorator with mock

from mock import patch

@task
@patch.multiple(settings, CELERY_TIMEZONE='time_zone')
def my_task(*args):
    #do your staff

I'm not tested it yet but it seems right. I hope i helped you :)

Maybe I'm misunderstanding the problem, but if you want to run tasks at a certain time in different time zones, could you not just offset the scheduled time by the hour difference between the time zones? For example, if I wanted a task to run at 5 PM in two different TZs:

# settings.py
CELERY_TIMEZONE = "US/Eastern"

CELERYBEAT_SCHEDULE = { 
    # Task to run in EST
    'schedule-my-est-task': {
        'task': 'path.to.my.est.task',
        'schedule': crontab(minute=0, hour=17),
    },
    # Task to run in UTC - hour time is offset
    'schedule-my-utc-task': {
        'task': 'path.to.my.utc.task',
        'schedule': crontab(minute=0, hour=10), 
    },
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!