这是以编程方式终止(取消)芹菜任务的最佳方式
Which is the best way to programatically terminate (cancel) a celery task
根据 Celery 的文档,我们不应该在 revoke()
函数中使用 terminate
选项来取消正在执行的任务:
The terminate option is a last resort for administrators when a task is stuck. It’s not for terminating the task, it’s for terminating the process that’s executing the task, and that process may have already started processing another task at the point when the signal is sent, so for this reason you must never call this programmatically.
http://docs.celeryproject.org/en/latest/userguide/workers.html#revoke-revoking-tasks
所以,我的问题是,如果我需要以编程方式取消一些 运行 任务,我应该如何正确地做?
如果您确实需要终止 运行 任务,在 revoke()
方法中使用 terminate=True
是正确的方法,也是您的最佳选择。问题是这样做并不能保证效果,或者更好地说,可能会产生负面影响。要了解原因,有必要了解撤销的工作原理以及 terminate=True
的作用。当您调用 revoke()
时,您正在通过代理向您的工作人员发送广播消息。这意味着在你意识到你 want/need 终止任务、发送撤销消息并接收到 worker 的控制命令之前,worker 可能已经完成任务,从队列中抓取另一个任务并开始正在努力。当它最终收到命令时,它只是终止工作进程,到那时,它可能已经在处理不同的任务。
如果您事先知道您可能需要中止任务并可以调整任务代码,您可以查看 abortable tasks。
根据 Celery 的文档,我们不应该在 revoke()
函数中使用 terminate
选项来取消正在执行的任务:
The terminate option is a last resort for administrators when a task is stuck. It’s not for terminating the task, it’s for terminating the process that’s executing the task, and that process may have already started processing another task at the point when the signal is sent, so for this reason you must never call this programmatically.
http://docs.celeryproject.org/en/latest/userguide/workers.html#revoke-revoking-tasks
所以,我的问题是,如果我需要以编程方式取消一些 运行 任务,我应该如何正确地做?
如果您确实需要终止 运行 任务,在 revoke()
方法中使用 terminate=True
是正确的方法,也是您的最佳选择。问题是这样做并不能保证效果,或者更好地说,可能会产生负面影响。要了解原因,有必要了解撤销的工作原理以及 terminate=True
的作用。当您调用 revoke()
时,您正在通过代理向您的工作人员发送广播消息。这意味着在你意识到你 want/need 终止任务、发送撤销消息并接收到 worker 的控制命令之前,worker 可能已经完成任务,从队列中抓取另一个任务并开始正在努力。当它最终收到命令时,它只是终止工作进程,到那时,它可能已经在处理不同的任务。
如果您事先知道您可能需要中止任务并可以调整任务代码,您可以查看 abortable tasks。