使用 Celery 的单个 Django 模型的每个对象的不同 crontab

Different crontab for each objects of single Django model using Celery

我能够创建 celery_beat_schedule 并且它有效。耶!

但我想知道是否有任何方法可以为同一 Django 模型的不同对象创建 cronjob。

Settings.py

CELERY_BEAT_SCHEDULE = {
    'ok': {
        'task' : 'bill.tasks.ok',
        'schedule' : crontab(minute=27, hour=0),
        # 'args' : (*args)
    }
}

bill/tasks.py

from celery import task
@task
def ok():
    bills = Bill.objects.all()
    for bill in bills:
        perform_something(bill)

感谢您的宝贵时间:)

Well I wouldn't be able to find how to run different crontab for each task instances. But there is another way to run. Just run your crontab on each hour and every time check if your query matches with the present time in tasks.py.

您可以在参数中指定值,然后使用它们过滤 QuerySet。

Settings.py

CELERY_BEAT_SCHEDULE = {
    'ok_27_0': {
        'task' : 'bill.tasks.ok',
        'schedule' : crontab(minute=27, hour=0),
        'args' : (27, 0)
    },
    'ok_5_any': {
        'task' : 'bill.tasks.ok',
        'schedule' : crontab(minute=5),
        'args' : (5, None)
    }
}

bill/tasks.py

from celery import task
@task
def ok(minute=None, hour=None):
    bills = Bill.objects.all()

    if minute is not None:
        bills = bills.filter(minute=minute)
    if hour is not None:
        bills = bills.filter(hour=hour)

    for bill in bills:
        perform_something(bill)

编辑:

您可能还想尝试绑定任务并查看是否可以在任务实例或其请求中找到任务的计划。这样您就不必在设置中重复自己。但是,我不知道这是否可能。

@task(bind=True)
def ok(self):
    self.request