简体   繁体   English

Django Celery定期任务示例

[英]Django Celery periodic task example

I need a minimum example to do periodic task (run some function after every 5 minutes, or run something at 12:00:00 etc.). 我需要一个最低限度的示例来执行定期任务(每5分钟运行一次功能,或在12:00:00运行某项,等等)。

In my myapp/tasks.py , I have, 在我的myapp/tasks.py中,

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


@periodic_task(run_every=(crontab(hour="*", minute=1)), name="run_every_1_minutes", ignore_result=True)
def return_5():
    return 5


@task
def test():
    return "test"

When I run celery workers it does show the tasks (given below) but does not return any values (in either terminal or flower). 当我运行芹菜工作者时,它确实显示了任务(如下所示),但没有返回任何值 (在终端或花中)。

[tasks]
  . mathematica.core.tasks.test
  . run_every_1_minutes

Please provide a minimum example or hints to achieve the desired results. 请提供一个最小的示例或提示以达到预期的效果。

Background: 背景:

I have a config/celery.py which contains the following: 我有一个config/celery.py ,其中包含以下内容:

import os
from celery import Celery

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local")

app = Celery('config')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()

And in my config/__init__.py , I have 在我的config/__init__.py

from .celery import app as celery_app

__all__ = ['celery_app']

I added a function something like below in myapp/tasks.py 我在myapp/tasks.py添加了类似于下面的功能

from celery import task

@task
def test():
    return "test"

When I run test.delay() from shell, it runs successfully and also shows the task information in flower 当我从shell运行test.delay()时,它成功运行并且还在花中显示任务信息

To run periodic task you should run celery beat also. 要运行定期任务,您还应该运行芹菜节拍 You can run it with this command: 您可以使用以下命令运行它:

celery -A proj beat

Or if you are using one worker: 或者,如果您使用的是一名工人:

celery -A proj worker -B

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM