Django 和 Celery 的示例:周期性任务 [英] Examples of Django and Celery: Periodic Tasks
问题描述
我一直在与 Django/Celery 文档作斗争,需要一些帮助.
I have been fighting the Django/Celery documentation for a while now and need some help.
我希望能够使用 django-celery 运行定期任务.我在互联网(和文档)中看到了几种不同的格式和模式,说明应该如何使用 Celery 实现这一目标......
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-celery 周期性任务的基本功能示例吗?特别是,我想知道我是否应该编写一个扩展 PeriodicTask 类的任务并注册它,或者我是否应该使用@periodic_task 装饰器,或者我是否应该使用@task 装饰器然后为任务的执行.
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.
我不介意这三种方式是否都可行,但我希望看到至少一种可行方式的示例.非常感谢您的帮助.
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.
推荐答案
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:
from celery.task.schedules import crontab
from celery.task import periodic_task
@periodic_task(run_every=crontab(minute="*/30"))
def process_clicks():
....
decorator 语法 只允许您转换现有函数/将任务转换为周期性任务,无需直接修改它们.
The decorator syntax simply allows you to turn an existing function/task into a periodic task without modifying them directly.
对于要执行的任务 celerybeat 必须正在运行.
这篇关于Django 和 Celery 的示例:周期性任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!