芹菜,在指定时间运行一次任务 [英] Celery, run task once at a specified time
问题描述
如何在给定的时间执行一次芹菜任务,但只能执行一次?
How can I run a celery task at a given time, but only once?
我阅读了文档,找不到任何示例。
I read the documentation and couldn't find any example of this.
推荐答案
如果您坚持使用Celery
要在指定的时间,在Celery中,您通常会使用 定期任务 ,它通常是一个重复执行的任务。
If you insist on using Celery
To run a task at a specified time, in Celery you would normally use a periodic task, which conventionally is a recurring task.
但是,您可以创建一个定期任务,该任务具有非常特定的时间表和条件,并且只发生一次
However, you may create a periodic task with a very specific schedule and condition that happens only once so effectively it runs only once.
不幸的是,我们只能指定很多,例如我们可以指定小时
,分钟
, day_of_month
和 month_of_year
,但是我们无法指定 year
Unfortunately we can only specify so much, e.g. we can specify hour
, minute
, day_of_month
and month_of_year
but we can't specify year
但是,您的任务每年最多可以运行1次,因此以下是一些解决方法:
However with that, your task would run at most 1 time for per year, so below are some workarounds:
运行后取消计划
取消计划运行起来应该相对容易(您有1年的时间!)
It should be relatively easy to unschedule it once it is ran (you have 1 year to do so!)
在任务完成时使用完成标志
在某个位置(磁盘或数据库)写入标志后,您可以可以首先检查任务是否之前运行过,即是否完成:退出
With a flag written somewhere (disk or DB), you can first check if the task has run before or not, i.e. if done: exit
退出年份不正确
,或者您想确保安全,只需将代码添加到检查年份的任务中即可,例如如果Year!= 2017:退出
。
您也可以完全跳过Celery并使用某些操作系统级别的工具,例如cron,用于类似UNIX的系统,此处更多内容。
You may also skip Celery altogether and use some OS level facility like cron for UNIX-like systems, more on that here.
总体思路保持不变。
这篇关于芹菜,在指定时间运行一次任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!