如何从以前的芹菜任务生成一个芹菜任务?

2024-09-30 04:38:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我可能用错了芹菜。但是我正在开发的聊天机器人需要芹菜和redis来完成异步任务。{我正在使用这个框架。在

我的特定用例当前要求我永远运行一个芹菜任务,并在这两个任务之间等待30分钟到3天的任意时间。像这样的东西

@celery.task
def myAsyncMethod():
    while true:
        timeToWait = getTimeToNextAlarm()
        sleep(timeToWait)
        sendOutMessages()

基本上,我有一个从不存在的异步进程。我很确定不应该用这种芹菜。所以我的问题是,如何创建一个处理第一个任务、生成一个任务并将其提交到celery queue并退出的celery任务。基本上,如下所示:

^{pr2}$

不一定是递归的,甚至像这样,但这是芹菜最初的用途(我相信是短期任务?)在

Tl;dr:如何从另一个任务中创建一个芹菜任务,并使原始任务退出?在

请告诉我是否应该进一步解释。谢谢。在


Tags: redis框架truetaskdef时间机器人sleep
2条回答

如果要从初始任务运行另一个任务,只需像通常使用^{},或^{}那样调用它:

@celery.task
def myImprovedTask():
    timeToWait = getTimeToNextAlarm()
    sleep(timeToWait)
    sendOutMessages()
    myImprovedTask.delay()

如果你再次调用同一个任务也没关系。它与delay()一起排队,返回原始任务,然后运行队列中的下一个任务。在


所有这些都是在一个假设下进行的,即您实际上是在异步地调用芹菜任务。有时情况并非如此,常见的罪魁祸首是^{}config选项。默认情况下,它被禁用,但是(来自docs):

If task_always_eager is True, all tasks will be executed locally by blocking until the task returns. apply_async() and Task.delay() will return an EagerResult instance, that emulates the API and behavior of AsyncResult, except the result is already evaluated.

That is, tasks will be executed locally instead of being sent to the queue.

所以,确保你的芹菜配置包括:

^{pr2}$

If the task isn’t registered in the current process you can use send_task() to call the task by name instead

如文档中所定义的http://docs.celeryproject.org/en/latest/reference/celery.html#celery.Celery.send_task

app.send_task('task_name')

这样做时,您必须显式地为任务命名,例如:

^{pr2}$

然后你就可以用:

app.send_task('myImprovedTask')

如果不喜欢这种方式(或者文件在同一个文件中),也可以用apply_async或{a3}来调用它:

myImprovedTask.delay()
myImprovedTask.apply_async()

相关问题 更多 >

    热门问题