Asynchronous Sum Calculation with Celery

  • Share this:

Code introduction


The code defines a Celery task that calculates the sum of two numbers asynchronously. It first creates a Celery application, then defines a task that accepts two parameters and returns their sum as the result. The main function `add_numbers` uses the `increment.delay()` method to asynchronously call this task and returns an asynchronous result, which is then fetched using the `get` method.


Technology Stack : The code uses the Celery package and RabbitMQ as the message broker.

Code Type : The type of code

Code Difficulty :


                
                    
from celery import Celery
import random

def random_task():
    app = Celery('tasks', broker='pyamqp://guest@localhost//')

    @app.task
    def increment(x, y):
        return x + y

    def add_numbers(a, b):
        result = increment.delay(a, b)
        return result.get(timeout=10)

    return add_numbers