Create celery tasks then run synchronously

后端 未结 2 556
暖寄归人
暖寄归人 2020-12-28 16:27

My app gathers a bunch of phone numbers on a page. Once the user hits the submit button I create a celery task to call each number and give a reminder message then redirect

相关标签:
2条回答
  • 2020-12-28 16:43

    if you want to fire each call one after another, why dont you wrap all the calls in one task

    @task
    def make_a_lot_of_calls(numbers):
        for num in numbers:
            # Assuming that reminder blocks till the call finishes
            reminder(number)
    
    def make_calls(request):
        make_a_lot_of_calls.delay(phone_numers)                          
        return redirect('live_call_updates') 
    
    0 讨论(0)
  • 2020-12-28 17:08

    If you look at the celery DOCS on tasks you see that to call a task synchronosuly, you use the apply() method as opposed to the apply_async() method.

    So in your case you could use:

     reminder.apply(args=[number])
    

    The DOCS also note that:
    If the CELERY_ALWAYS_EAGER setting is set, it will be replaced by a local apply() call instead.

    Thanks to @JivanAmara who in the comments reiterated that when using apply(), the task will run locally(in the server/computer in which its called). And this can have ramifications, if you intended to run your tasks across multiple servers/machines.

    0 讨论(0)
提交回复
热议问题