运行 随机时间的 celery 任务

run celery tasks in random times

我需要在随机时间 运行 几个芹菜任务 - 每个 运行 应该在一个新的随机时间 - 随机数应该在每个 运行 生成。
我过去所做的是:

 "my_task": {
     "task": "path.to.my_task",
     "schedule": crontab(minute='*/%s' % rand),
 },
rand = random(1,12)

但是这段代码不适合我的需要,还有更多:
1. 我需要不同的(每个租户尽可能使用 random0 编号
2. 每次都会生成不同的数字,而不仅仅是 settings.py 加载(一次)

我尝试按照 THIS 回答中的说明覆盖 Schedule 但它没有用,有更好的方法吗?我错过了什么吗?

(例如,在租户 A 中,任务将在 23 日和次日 8 点 运行,而在租户 B 中,任务将在 4 日和次日 20 日 运行 等)

谢谢!

========更新====

在得到很好的答案后,我在我的任务中添加了选项,并按照建议的 apply_asynch 方法处理它 -

"my-task": {  # deprecated task
               "task": "mdm_sync.tasks.test_task",
               # "schedule": new_sc(),
               "schedule": crontab(minute=39, hour=11),
                "options": {
                    "eta": datetime.utcnow()
                }
},


entry.options["eta"] = datetime.datetime.utcnow() + datetime.timedelta(seconds=random(3600,12*3600)

效果很好!

我遇到了一个类似的问题,我不得不在 随机用户 之间以 随机间隔生成 facebook 之类的通知时间

最初我也和你一样,使用random函数将minute值赋给crontab。但是,由于 settings.pycelery.py 在您点击 python manage.py runserver 时仅加载一次,该随机函数仅运行一次,因此该随机值仅被选择一次,例如 5分钟7 分钟,但此随机值用于每 5 或 7 分钟重复一次任务,因此使任务 定期重复 .

所以,你需要做的是,而不是在 settings.pycelery.py 中定义任务的时间,你需要 递归地 调用函数/ 方法在您的 tasks.py 中。但是这里的关键是,你需要递归异步调用同一个函数,而异步调用的同时,需要传递一个参数delay其值将使用随机函数

计算

查看我的 tasks.py -> https://github.com/ankushrgv/notification/blob/master/apps/notifications/tasks.py

celery.py -> https://github.com/ankushrgv/notification/blob/master/config/celery.py

您必须 python manage.py shell 然后从那里调用函数/方法一次以开始递归。

类似

`myFunction().apply_async()`

在我的情况下,它曾经是

`CreateNotifications().apply_async()`