shi*_*etz 6 python django celery django-celery celerybeat
我每 30 秒有一个计划的 celery 运行任务。我有一个每天作为任务运行,另一个每周在用户指定的时间和星期几运行。它检查“开始时间”和“下一个预定日期”。在任务完成之前,下一个计划日期不会更新。
但是,我想知道如何确保 celery beat 只运行一次任务。我现在看到,芹菜将多次运行某个任务,直到该任务的下一个预定日期更新。
小智 5
为此,您需要实现某种“分布式锁”,而解决此问题的一种简单可靠的方法是使用带有 memcached 后端的 django 缓存,并在任务开始时在其中设置一个“标志”,然后就在它之前完成删除该标志。另一种选择是使用“redis”锁作为“分布式锁”。使用 django 缓存 memcached 作为后端的示例:
@shared_task
def my_task(arg1, arg2, lock_expire=300):
lock_key = 'my_task'
acquire_lock = lambda: cache.add(lock_key, '1', lock_expire)
release_lock = lambda: cache.delete(lock_key)
if acquire_lock():
try:
# Execute your code here!
except Exception:
# error handling here
finally:
# release allow other task to execute
release_lock()
else:
print("Other task is running, skipping")
Run Code Online (Sandbox Code Playgroud)
上面的代码实现了一个“分布式锁”,以确保无论您尝试再次执行多少次,都只能运行一个任务。只有一个任务可以获取锁:),另一个任务将跳过“主块”并完成。这对你有意义吗?
玩得开心!