You can download this code by clicking the button below.
This code is now available for download.
This function defines a Celery task that generates a random number and runs it with a delay. It uses the Celery framework for asynchronous task processing and Python's random module to generate random numbers.
Technology Stack : This function defines a Celery task that generates a random number and runs it with a delay. It uses the Celery framework for asynchronous task processing and Python's random module to generate random numbers.
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():
# Generate a random number between 1 and 100
return random.randint(1, 100)
def delay_task():
# Schedule a task to run after a random delay
task = app.send_task('tasks.generate_random_number', (result,), countdown=random.randint(1, 5))
return task.get(timeout)
try:
# Run the delayed task and wait for the result
result = delay_task()
logger.info(f'Random number generated: {result}')
return result
except Exception as e:
logger.error(f'Error occurred: {e}')
return None