让芹菜等待任务完成 [英] Make celery wait for task to finish

查看:40
本文介绍了让芹菜等待任务完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望 celery 等待特定任务完成,因此我在 celery 本身旁边安装了 celery-results-backend.但我不明白我必须如何编写任务调用才能等待,因为我目前收到以下错误:

I want celery to wait for a specific task to finish, therefore I installed the celery-results-backend beside celery itself. But I don't understand how I have to write my task call in order to wait as I currently get the following error:

example_task() missing 1 required positional argument: 'user_pk'

views.py:

def example(request):
    user = request.user
    if request.method == 'GET':
        result = example_taks.apply_async(user_pk=user.pk)
        result_output = result.wait(timeout=None, interval=0.5)
        return redirect('something')
    else:
        args = {'user': user}
        return redirect(reverse('something'), args)

tasks.py:

def example_task(user_pk):
    user = User.objects.get(pk=user_pk)
    try:
       ...

以前我是这样称呼会谈的:

previously I called the talks like that:

def example(request):
    user = request.user
    if request.method == 'GET':
    example_task.delay(request.user.pk)
    ...

这工作正常,但没有等待任务完成.

This was working fine but did not wait for task to finish.

如果我这样做:

result = allocate_new_bch_address.apply_async(request.user.pk)

我也收到一个错误:

example_task() argument after * must be an iterable, not UUID

推荐答案

首先,您使用的 apply_async() 是错误的.该函数接受打包为元组 (args) 和字典 (kwargs) 的任务参数,如 此处.这是因为您可以指定定义任务运行方式的附加参数.另一方面,delay() 只接受你的任务的 args 和 kwargs.delay() 在大多数情况下就足够了.

First, you're using apply_async() wrong. The function accepts your task's arguments packed as a tuple (args) and dictionary (kwargs) as seen here. This is because you can specify additional parameters that define how the task should run. On the other hand, delay() only accepts your task's args and kwargs. delay() is sufficient in most cases.

你可以这样做:

 example_taks.apply_async(kwargs={"user_pk":user.pk})

或者这个:

example_tasks.delay(user_pk=user.pk)

您也可以使用位置参数,但我建议尽可能使用 kwargs.

You can also use positional arguments but I would recommend using kwargs when possible.

其次,一旦提交就等待异步任务违背了 Celery 的目的.要等待任务完成,您需要调用 get() 结果:

Second, waiting for an async task as soon as submitting it defeats the purpose of Celery. To wait for a task to finish you need to call get() on the result:

result = example_tasks.apply_async(kwargs={"user_pk":user.pk})
result_output = result.get()

这篇关于让芹菜等待任务完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆