You can download this code by clicking the button below.
This code is now available for download.
This function uses the Celery library to create a background task that generates a random number and waits for the result. It demonstrates how to handle asynchronous tasks with Celery.
Technology Stack : Celery, Python Standard Library
Code Type : Celery mission
Code Difficulty : Intermediate
def random_task(result, timeout=10):
from celery import Celery
from celery.utils.log import get_task_logger
import random
import time
app = Celery('tasks', broker='pyamqp://guest@localhost//')
logger = get_task_logger(__name__)
def generate_random_number():
return random.randint(1, 100)
def wait_for_result():
result.get(timeout=timeout)
@app.task
def background_task():
num = generate_random_number()
logger.info(f'Generated number: {num}')
return num
task = background_task.delay()
wait_for_result()
return result.get()