[英]how to execute celery tasks conditionally python
I am new to celery. 我是芹菜的新手。 I have a celery task that needs to be executed when a condition is met.
我有一个芹菜任务,需要在满足条件时执行。 Otherwise retry after few minutes.
否则几分钟后重试。 From the below code, I am stuck at how to retry the same task in else condition?
从下面的代码中,我坚持如何在else条件下重试相同的任务? Appreciate your help.
感谢您的帮助。
@app.task(bind=True,soft_time_limit=4 * 3600)
def task_message_queue(id, name=None, tid=None, src=None, dest=None, queue="MessageQueue"):
ThreadLocalStore().set_data({"id": id, "tid": tid, "name": name,"src": src, "dest":dest})
num_files = os.popen("find %s -type f | wc -l" % dest).read().strip().split('\n')[0]
if num_files < 20:
#Move files from src to destination
else:
#wait for 2 minutes and retry the task
Instead of relying on retry you could also just trigger the task again. 您可以再次触发任务,而不是依赖重试。
from celery.task import task
@app.task(bind=True,soft_time_limit=4 * 3600)
def task_message_queue(self, id, name=None, tid=None, src=None, dest=None, queue="MessageQueue"):
ThreadLocalStore().set_data({"id": id, "tid": tid, "name": name,"src": src, "dest":dest})
num_files = os.popen("find %s -type f | wc -l" % dest).read().strip().split('\n')[0]
if num_files < 20:
#Move files from src to destination
else:
# Trigger the task again in 120 seconds.
task_message_queue.apply_async(countdown=120)
You have to call retry
to make celery retry the task and you can set the countdown so celery will wait for that much time and retry the task. 您必须调用
retry
以使芹菜重试该任务,您可以设置倒计时,以便芹菜将等待那么长时间并重试该任务。 Below is the code borrowed from official celery docs . 以下是从官方芹菜文档借来的代码。 Modify the
@task
decorator according to your needs and also self.retry
根据您的需要和
self.retry
修改@task
装饰器
from celery.task import task
@app.task(bind=True,soft_time_limit=4 * 3600)
def task_message_queue(self, id, name=None, tid=None, src=None, dest=None, queue="MessageQueue"):
ThreadLocalStore().set_data({"id": id, "tid": tid, "name": name,"src": src, "dest":dest})
num_files = os.popen("find %s -type f | wc -l" % dest).read().strip().split('\n')[0]
try:
if num_files < 20:
#Move files from src to destination
else:
raise SOME_EXCEPTION
#wait for 2 minutes and retry the task
except SOME_EXCEPTION as exc:
self.retry(exc=exc, countdown=TIME_TO_WAIT_BEFORE_RETRY)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.