Celery Scheduled Addition Task Example

  • Share this:

Code introduction


This code defines a Celery task that runs an addition task every day at midnight, and demonstrates how to use Celery's scheduled tasks and task invocation.


Technology Stack : Celery, random, celery, crontab

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
def random_task(x, y):
    import random
    import celery
    from celery.schedules import crontab

    app = celery.Celery('tasks', broker='pyamqp://guest@localhost//')

    # Schedule a task to be executed every day at midnight
    app.conf.beat_schedule = {
        'run-every-day': {
            'task': 'tasks.add',
            'schedule': crontab(hour=0, minute=0),
        },
    }

    # Define a task to add two numbers
    @app.task
    def add(x, y):
        return x + y

    # Generate a random number and use the add task to add x and y
    result = add.delay(random.randint(1, 100), y)
    return result.get()