简体   繁体   English

如何在 django 中只运行一次 celery 任务?

[英]how can I run celery task only once in django?

from __future__ import absolute_import, unicode_literals

from celery import shared_task
from celery.task import periodic_task
from celery.schedules import crontab
from datetime import timedelta



@periodic_task(run_every=(crontab(minute='*/1')), name='greeting_task')
def greeting_task():
    print('hello Dias!')

Can I create a function that runs only once at certain time with crontab?我可以使用 crontab 创建一个在特定时间只运行一次的 function 吗? PLEASE, HELP!!!请帮忙!!! thanks in advance!提前致谢!

If you are using Django-Celery-Beat , it has the ability to create tasks that run only once at a specific date/time using the ClockedSchedule model.如果您使用的是Django-Celery-Beat ,它可以使用ClockedSchedule model 创建在特定日期/时间仅运行一次的任务。 It's not in the documentation for some reason but you can easily configure it through the Django Admin.由于某种原因,它不在文档中,但您可以通过 Django 管理员轻松配置它。

You need to change the parameters for crontab .您需要更改crontab的参数。

Example: If you want the task to be run once at 5AM everyday:示例:如果您希望任务在每天凌晨 5 点运行一次:

@periodic_task(run_every=(crontab(minute='0', hour='5')), name='greeting_task')
def greeting_task():
    print('hello Dias!')

crontab(minute='*/1') will run the task at every minute. crontab(minute='*/1')将每分钟运行一次任务。 Read about crontab syntax here: https://en.wikipedia.org/wiki/Cron在此处阅读有关 crontab 语法的信息: https://en.wikipedia.org/wiki/Cron

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

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