gpt4 book ai didi

Django celery : scheduling recurring task but with fixed start date

转载 作者:行者123 更新时间:2023-12-02 05:41:40 27 4
gpt4 key购买 nike

目前,djcelery 允许我通过PeriodicTask 模型安排重复任务。例如,任务按每分钟等间隔运行,或者按 crontab 指定的间隔(如每月 1 日中午)运行。然而,我真正想做的是将任务安排在固定日期,然后按一定时间间隔重复。例如,首次运行时间为 2016 年 3 月 3 日 2:00,此后每小时运行一次。

有没有办法在 django 和 celery 中实现这一点(有或没有 djcelery)?谢谢

最佳答案

正如 the docs 中所述,您可以实现自己的自定义调度程序。您应该重写 is_due 方法,该方法决定是否到了运行任务的时间。

下面是一个概念验证(我还没有检查它是否有错误)。请注意,__reduce__ 方法也被重写,以便新参数也被序列化。

import celery.schedules.schedule

class myschedule(celery.schedules.schedule):

def __init__(self, *args, **kwargs):
super(myschedule, self).__init__(*args, **kwargs)
self.start_date = kwargs.get('start_date', None)

def is_due(self, last_run_at):
if self.start_date is not None and self.now() < self.start_date:
return (False, 20) # try again in 20 seconds
return super(myschedule, self).is_due(last_run_at)

def __reduce__(self):
return self.__class__, (self.run_every, self.relative, self.nowfun, self.start_date)

然后在配置中使用它:

CELERYBEAT_SCHEDULE = {
'add-every-30-seconds': {
'task': 'tasks.add',
'schedule': myschedule(timedelta(seconds=30), start_date=start_date),
'args': (16, 16)
},
}

关于 Django celery : scheduling recurring task but with fixed start date,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35377115/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com