Bird
Raised Fist0
Flaskframework~20 mins

Periodic tasks with Celery Beat in Flask - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Celery Beat Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when a periodic task is scheduled with Celery Beat?

Consider a Flask app using Celery with Celery Beat to schedule a task every minute. What is the expected behavior when the scheduler triggers the task?

Flask
from celery import Celery
from celery.schedules import crontab

app = Celery('tasks', broker='redis://localhost:6379/0')

@app.task
def send_report():
    print('Report sent')

app.conf.beat_schedule = {
    'send-report-every-minute': {
        'task': 'tasks.send_report',
        'schedule': crontab(minute='*'),
    },
}

app.conf.timezone = 'UTC'
AThe send_report task runs only if manually called in the Flask app code.
BThe send_report task runs only once when the app starts.
CThe send_report task runs every second due to the crontab schedule.
DThe send_report task runs automatically every minute without manual triggering.
Attempts:
2 left
💡 Hint

Think about what Celery Beat does with the schedule configuration.

📝 Syntax
intermediate
2:00remaining
Identify the syntax error in this Celery Beat schedule configuration

Which option shows the correct way to define a periodic task schedule in Celery Beat?

Flask
app.conf.beat_schedule = {
    'task-name': {
        'task': 'tasks.example_task',
        'schedule': crontab(hour=0, minute=0)
    }
}
Aapp.conf.beat_schedule = {'task-name': {'task': 'tasks.example_task', 'schedule': crontab(hour=0, minute=0)}}
Bapp.conf.beat_schedule = {'task-name': {'task': 'tasks.example_task', 'schedule': crontab(hour=0, minute=0),}}
Capp.conf.beat_schedule = {'task-name': {'task': 'tasks.example_task', 'schedule': crontab(hour=0 minute=0)}}
Dapp.conf.beat_schedule = {'task-name': {'task': 'tasks.example_task', 'schedule': crontab(hour=0; minute=0)}}
Attempts:
2 left
💡 Hint

Check for missing commas or invalid separators in the dictionary.

🔧 Debug
advanced
2:00remaining
Why does the periodic task not run even though Celery Beat is configured?

A Flask app has Celery and Celery Beat configured with a periodic task. The task is defined and scheduled correctly, but it never runs. What is the most likely cause?

Flask
from celery import Celery

app = Celery('tasks', broker='redis://localhost:6379/0')

@app.task
def cleanup():
    print('Cleanup done')

app.conf.beat_schedule = {
    'cleanup-task': {
        'task': 'tasks.cleanup',
        'schedule': 60.0,
    },
}

app.conf.timezone = 'UTC'
AThe Celery Beat scheduler process is not running alongside the worker.
BThe task name 'tasks.cleanup' is incorrect and should be 'cleanup'.
CThe schedule value 60.0 is invalid and must be a crontab object.
DThe broker URL is missing the password for Redis.
Attempts:
2 left
💡 Hint

Think about what components must run for periodic tasks to execute.

❓ state_output
advanced
2:00remaining
What is the output of this periodic task with state update?

Given this Celery task that updates a state dictionary each time it runs, what will be the value of state['count'] after 3 executions triggered by Celery Beat?

Flask
state = {'count': 0}

@app.task
def increment():
    state['count'] += 1
    print(f"Count is {state['count']}")

app.conf.beat_schedule = {
    'increment-task': {
        'task': 'tasks.increment',
        'schedule': 10.0,
    },
}

app.conf.timezone = 'UTC'
ACount is 1 printed three times; state['count'] remains 1 due to task isolation.
BCount is 3 printed once; state['count'] resets after each run.
CCount is 0 printed three times; state['count'] never increments.
DCount is 3 printed three times; state['count'] is 3 after 3 runs.
Attempts:
2 left
💡 Hint

Consider how Celery tasks run in separate worker processes.

🧠 Conceptual
expert
3:00remaining
How to ensure a periodic task runs exactly once in a distributed Celery worker setup?

You have multiple Celery workers running in parallel with Celery Beat scheduling a periodic task. How do you guarantee the task runs only once per schedule, not multiple times?

ARun multiple Celery Beat schedulers to balance the load.
BConfigure each worker with a unique queue and schedule the task on all queues.
CUse a distributed lock or singleton pattern to prevent multiple executions.
DSet the task's schedule to crontab with seconds precision.
Attempts:
2 left
💡 Hint

Think about how to avoid race conditions in distributed systems.

Practice

(1/5)
1. What is the main purpose of Celery Beat in a Flask application?
easy
A. To schedule tasks to run automatically at specific times
B. To handle HTTP requests asynchronously
C. To manage database migrations
D. To serve static files efficiently

Solution

  1. Step 1: Understand Celery Beat's role

    Celery Beat is a scheduler that triggers tasks periodically without manual intervention.
  2. Step 2: Compare with other options

    Handling HTTP requests, managing migrations, and serving static files are unrelated to scheduling tasks.
  3. Final Answer:

    To schedule tasks to run automatically at specific times -> Option A
  4. Quick Check:

    Celery Beat = Task scheduler [OK]
Hint: Celery Beat is all about timing tasks automatically [OK]
Common Mistakes:
  • Confusing Celery Beat with request handling
  • Thinking it manages database or static files
  • Assuming it runs tasks only once
2. Which of the following is the correct way to define a periodic task in Celery Beat using Flask?
easy
A. @app.route('/task')\ndef my_task():\n print('Hello')
B. @celery.task\ndef my_task():\n print('Hello')
C. def my_task():\n print('Hello')
D. @celery.task\nasync def my_task():\n print('Hello')

Solution

  1. Step 1: Identify task decorator

    Periodic tasks in Celery are defined with the @celery.task decorator.
  2. Step 2: Check syntax correctness

    @celery.task\ndef my_task():\n print('Hello') correctly uses @celery.task and a normal function. @app.route('/task')\ndef my_task():\n print('Hello') uses Flask route decorator, which is unrelated. def my_task():\n print('Hello') lacks any decorator. @celery.task\nasync def my_task():\n print('Hello') uses async which is not standard for Celery tasks.
  3. Final Answer:

    @celery.task\ndef my_task():\n print('Hello') -> Option B
  4. Quick Check:

    Use @celery.task to define Celery tasks [OK]
Hint: Use @celery.task decorator for Celery tasks [OK]
Common Mistakes:
  • Using Flask route decorator instead of @celery.task
  • Defining tasks without any decorator
  • Using async def which Celery does not support by default
3. Given this Celery Beat schedule snippet, what will happen?
beat_schedule = {
'print-every-10-seconds': {
'task': 'app.print_message',
'schedule': 10,
},
}
medium
A. The task runs once after 10 seconds
B. The task runs every 10 minutes
C. The task 'print_message' runs every 10 seconds
D. This code causes a syntax error

Solution

  1. Step 1: Understand the schedule value

    The 'schedule' key with value 10 means the task runs every 10 seconds.
  2. Step 2: Confirm task repetition

    Celery Beat schedules tasks repeatedly at the interval given, so it runs every 10 seconds, not once or every 10 minutes.
  3. Final Answer:

    The task 'print_message' runs every 10 seconds -> Option C
  4. Quick Check:

    Schedule=10 means every 10 seconds [OK]
Hint: Schedule number means seconds interval by default [OK]
Common Mistakes:
  • Thinking schedule is minutes instead of seconds
  • Assuming task runs only once
  • Confusing syntax with crontab format
4. Identify the error in this Celery Beat configuration:
beat_schedule = {
'task1': {
'task': 'app.task1',
'schedule': crontab(minute='*/5')
},
'task2': {
'task': 'app.task2',
'schedule': '10',
}
}
medium
A. The dictionary keys 'task1' and 'task2' must be integers
B. 'task' names must be functions, not strings
C. Missing import for crontab causes runtime error
D. 'schedule' for 'task2' should be an integer or crontab, not a string

Solution

  1. Step 1: Check 'schedule' types

    For 'task1', schedule uses crontab correctly. For 'task2', schedule is a string '10', which should be an integer 10 or a crontab object.
  2. Step 2: Validate other parts

    Task names as strings are correct references. Import errors are not shown here. Dictionary keys can be strings.
  3. Final Answer:

    'schedule' for 'task2' should be an integer or crontab, not a string -> Option D
  4. Quick Check:

    Schedule must be int or crontab, not string [OK]
Hint: Schedule values must be int or crontab, not quoted strings [OK]
Common Mistakes:
  • Using string instead of int for schedule interval
  • Confusing task names with function objects
  • Assuming dictionary keys must be integers
5. You want to run a Flask Celery task every Monday at 8:30 AM using Celery Beat. Which beat_schedule entry is correct?
hard
A. {'task': 'app.weekly_task', 'schedule': crontab(hour=8, minute=30, day_of_week='mon')}
B. {'task': 'app.weekly_task', 'schedule': crontab(hour=8, minute=30, day_of_week=2)}
C. {'task': 'app.weekly_task', 'schedule': crontab(hour=8, minute=30, day_of_week='tue')}
D. {'task': 'app.weekly_task', 'schedule': crontab(hour=8, minute=30, day_of_week='Monday')}

Solution

  1. Step 1: Understand crontab day_of_week format

    Celery's crontab accepts day_of_week as string names like 'mon', 'tue', or integers 0-6 (0=Sunday).
  2. Step 2: Evaluate options

    {'task': 'app.weekly_task', 'schedule': crontab(hour=8, minute=30, day_of_week='mon')} uses 'mon' string which is correct. {'task': 'app.weekly_task', 'schedule': crontab(hour=8, minute=30, day_of_week=2)} uses integer 2 which is Tuesday (0=Sunday). {'task': 'app.weekly_task', 'schedule': crontab(hour=8, minute=30, day_of_week='tue')} uses 'tue' string which is Tuesday. {'task': 'app.weekly_task', 'schedule': crontab(hour=8, minute=30, day_of_week='Monday')} uses 'Monday' full name which is not supported.
  3. Final Answer:

    {'task': 'app.weekly_task', 'schedule': crontab(hour=8, minute=30, day_of_week='mon')} -> Option A
  4. Quick Check:

    Use 'mon' string for Monday in crontab [OK]
Hint: Use three-letter lowercase day names like 'mon' for crontab [OK]
Common Mistakes:
  • Using full day names like 'Monday' instead of 'mon'
  • Using string numbers like '1' instead of integers or names
  • Confusing day_of_week numbering starting at Sunday
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard