Celery - 获取当前任务的任务ID
如何从任务中获取任务的 task_id 值?这是我的代码:
from celery.decorators import task
from django.core.cache import cache
@task
def do_job(path):
"Performs an operation on a file"
# ... Code to perform the operation ...
cache.set(current_task_id, operation_results)
这个想法是,当我创建任务的新实例时,我从任务对象中检索 task_id
。然后我使用任务 ID 来确定任务是否已完成。我不想通过path
值跟踪任务,因为文件在任务完成后被“清理”,并且可能存在也可能不存在。
在上面的例子中,我如何获取current_task_id
的值?
How can I get the task_id value for a task from within the task? Here's my code:
from celery.decorators import task
from django.core.cache import cache
@task
def do_job(path):
"Performs an operation on a file"
# ... Code to perform the operation ...
cache.set(current_task_id, operation_results)
The idea is that when I create a new instance of the task, I retrieve the task_id
from the task object. I then use the task id to determine whether the task has completed. I don't want to keep track of the task by the path
value because the file is "cleaned up" after the task completes, and may or may not exist.
In the above example, how would I get the value of current_task_id
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
更新:使用 Balthazar 对 Celery 3.1+ 的答案,
请随意投票支持他的答案。
旧答案:
从 Celery 2.2.0 开始,与当前执行任务相关的信息被保存到
task.request
(称为“上下文”)。因此,您应该从此上下文中获取任务 ID(而不是从关键字参数中获取,该参数已弃用):所有可用字段的列表记录在此处:
http://celery.readthedocs.org/en/latest /userguide/tasks.html?highlight=requestcontext#context
UPDATE: use Balthazar's answer for Celery 3.1+
Feel free to upvote his answer.
Old answer:
Since Celery 2.2.0, information related to the currently executed task is saved to
task.request
(it's called «the context»). So you should get task id from this context (not from keyword arguments, which are deprecated):The list of all available fields is documented here:
http://celery.readthedocs.org/en/latest/userguide/tasks.html?highlight=requestcontext#context
从 celery 3.1 开始,您可以使用
bind
装饰器参数,并可以访问当前请求:As of celery 3.1, you can use the
bind
decorator argument, and have access to the current request:如果任务接受,Celery 确实会设置一些默认关键字参数。
(您可以通过使用 **kwargs 接受它们,或专门列出它们)
默认关键字参数的列表记录在此处:
http://ask.github.com/celery/userguide/tasks .html#默认关键字参数
Celery does set some default keyword arguments if the task accepts them.
(you can accept them by either using **kwargs, or list them specifically)
The list of default keyword arguments is documented here:
http://ask.github.com/celery/userguide/tasks.html#default-keyword-arguments