Random Mathematical Task Execution with Celery

  • Share this:

Code introduction


This function is a Celery task that randomly selects two input arguments to perform mathematical operations and returns the result. If the task execution time exceeds the predefined time limit, it logs an error and returns None.


Technology Stack : Celery, Python, random, celery.utils.log, celery.exceptions

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
def random_task(arg1, arg2):
    from celery.utils.log import get_task_logger
    import random
    from celery.exceptions import SoftTimeLimitExceededError

    logger = get_task_logger(__name__)
    
    try:
        # Simulate a time-consuming task
        result = random.choice([arg1, arg2, arg1 + arg2, arg1 - arg2, arg1 * arg2, arg1 / arg2])
        return result
    except SoftTimeLimitExceededError:
        logger.error("The task exceeded the time limit.")
        return None