Django 和 Celery 的示例:定期任务

发布于 2024-12-17 18:14:28 字数 335 浏览 4 评论 0原文

我已经与 Django/Celery 文档作斗争一段时间了,需要一些帮助。

我希望能够使用 django-celery 运行定期任务。我在互联网(和文档)上看到了几种不同的格式和模式,关于如何使用 Celery 来实现这一目标...

有人可以帮助提供一个 django-celery 的创建、注册和执行的基本功能示例吗?周期性任务?特别是,我想知道是否应该编写一个扩展PeriodicTask类的任务并注册它,或者是否应该使用@periodic_task装饰器,或者是否应该使用@task装饰器,然后为该任务设置时间表执行。

我不介意这三种方法是否都可行,但我想看到至少一种有效方法的示例。非常感谢您的帮助。

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

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...

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小姐丶请自重 2024-12-24 18:14:28

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

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()

您可以使用装饰器编写相同的任务:

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

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

装饰器语法简单地允许您可以将现有功能/任务转变为周期性任务,而无需直接修改它们。

对于要执行的任务 celerybeat 必须正在运行< /a>.

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:

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.

For the tasks to be executed celerybeat must be running.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文