Django和芹菜的例子:周期性任务

时间:2021-01-22 19:18:59

I have been fighting the Django/Celery documentation for a while now and need some help.

我已经和Django/芹菜文档斗争了一段时间,需要一些帮助。

I would like to be able to run Periodic Tasks using django-celery. I have seen around the internet (and the documentation) several different formats and schemas for how one should go about achieving this using Celery...

我希望能够使用django-芹菜执行周期性任务。我在互联网上(和文档上)看到了几种不同的格式和模式,说明人们应该如何使用芹菜来实现这一点……

Can someone help with a basic, functioning example of the creation, registration and execution of a django-celery periodic task? In particular, I want to know whether I should write a task that extends the PeriodicTask class and register that, or whether I should use the @periodic_task decorator, or whether I should use the @task decorator and then set up a schedule for the task's execution.

有人能帮助创建、注册和执行一个django-芹菜周期任务的基本的、有效的示例吗?特别是,我想知道我是应该编写一个扩展PeriodicTask类并进行注册的任务,还是应该使用@periodic_task decorator,还是应该使用@task decorator,然后设置任务执行的调度。

I don't mind if all three ways are possible, but I would like to see an example of at least one way that works. Really appreciate your help.

我不介意这三种方法是否都可能,但我希望看到至少一种方法的示例。非常感谢你的帮助。

1 个解决方案

#1


37  

What's wrong with the example from the docs?

文档中的例子有什么问题?

from celery.task import PeriodicTask
from clickmuncher.messaging import process_clicks
from datetime import timedelta


class ProcessClicksTask(PeriodicTask):
    run_every = timedelta(minutes=30)

    def run(self, **kwargs):
        process_clicks()

You could write the same task using a decorator:

您可以使用decorator编写相同的任务:

from celery.task.schedules import crontab
from celery.task import periodic_task

@periodic_task(run_every=crontab(minute="*/30"))
def process_clicks():
    ....

The decorator syntax simply allows you to turn an existing function/task into a periodic task without modifying them directly.

decorator语法只允许您将现有的函数/任务转换为周期任务,而无需直接修改它们。

For the tasks to be executed celerybeat must be running.

要执行的任务,赛扬拍必须运行。

#1


37  

What's wrong with the example from the docs?

文档中的例子有什么问题?

from celery.task import PeriodicTask
from clickmuncher.messaging import process_clicks
from datetime import timedelta


class ProcessClicksTask(PeriodicTask):
    run_every = timedelta(minutes=30)

    def run(self, **kwargs):
        process_clicks()

You could write the same task using a decorator:

您可以使用decorator编写相同的任务:

from celery.task.schedules import crontab
from celery.task import periodic_task

@periodic_task(run_every=crontab(minute="*/30"))
def process_clicks():
    ....

The decorator syntax simply allows you to turn an existing function/task into a periodic task without modifying them directly.

decorator语法只允许您将现有的函数/任务转换为周期任务,而无需直接修改它们。

For the tasks to be executed celerybeat must be running.

要执行的任务,赛扬拍必须运行。