|
======================== |
|
CODE SNIPPETS |
|
======================== |
|
TITLE: Celery Beat Schedule Setting |
|
DESCRIPTION: The `beat_schedule` setting defines the periodic task schedule used by `celery beat`. It defaults to an empty mapping (`{}`) and refers to `beat-entries` for details. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/configuration.rst#_snippet_193 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
beat_schedule: |
|
Default: {} |
|
Description: The periodic task schedule used by `celery beat`. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Configure Celery Broadcast Routing with Beat Schedule |
|
DESCRIPTION: This Python example illustrates how to integrate broadcast routing with `celery beat` schedules. It shows how to define a periodic task that uses a broadcast exchange, ensuring the scheduled task is sent to every worker. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/routing.rst#_snippet_47 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
from kombu.common import Broadcast |
|
from celery.schedules import crontab |
|
|
|
app.conf.task_queues = (Broadcast('broadcast_tasks'),) |
|
|
|
app.conf.beat_schedule = { |
|
'test-task': { |
|
'task': 'tasks.reload_cache', |
|
'schedule': crontab(minute=0, hour='*/3'), |
|
'options': {'exchange': 'broadcast_tasks'} |
|
}, |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Celery Solar Schedule Configuration Example |
|
DESCRIPTION: Demonstrates how to configure a Celery beat schedule to execute a task at a specific solar event (e.g., sunset) for a given latitude and longitude using the `celery.schedules.solar` function. This example schedules a task to run at sunset in Melbourne. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/periodic-tasks.rst#_snippet_9 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
from celery.schedules import solar |
|
|
|
app.conf.beat_schedule = { |
|
# Executes at sunset in Melbourne |
|
'add-at-melbourne-sunset': { |
|
'task': 'tasks.add', |
|
'schedule': solar('sunset', -37.81753, 144.96715), |
|
'args': (16, 16), |
|
}, |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Celery Crontab Schedule Expression Examples |
|
DESCRIPTION: This section provides various examples of `celery.schedules.crontab` expressions, illustrating how to define different periodic schedules, from every minute to specific hours and days of the week. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/periodic-tasks.rst#_snippet_7 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
crontab(): Execute every minute. |
|
crontab(minute=0, hour=0): Execute daily at midnight. |
|
crontab(minute=0, hour='*/3'): Execute every three hours (midnight, 3am, 6am, 9am, noon, 3pm, 6pm, 9pm). |
|
crontab(minute=0, hour='0,3,6,9,12,15,18,21'): Same as previous. |
|
crontab(minute='*/15'): Execute every 15 minutes. |
|
crontab(day_of_week='sunday'): Execute every minute (!) on Sundays. |
|
crontab(minute='*', hour='*', day_of_week='sun'): Same as previous. |
|
crontab(minute='*/10', hour='3,17,22', day_of_week='thu,fri'): Execute every ten minutes, but only between 3-4 am, 5-6 pm, and 10-11 pm on Thursdays or Fridays. |
|
crontab(minute=0, hour='*/2,*/3'): Execute every even hour, and every hour divisible by three. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Celery Task.apply_async Method for Scheduled Execution |
|
DESCRIPTION: The `Task.apply_async` method allows scheduling a task to execute at a specific future time using the `eta` argument. While useful for short-term scheduling, using distant `eta` times is discouraged; for long-term or recurring schedules, Celery's periodic tasks (via `celery-beat`) are preferred. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/faq.rst#_snippet_21 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
Task.apply_async(eta=datetime): |
|
Parameters: |
|
eta (datetime): The exact time at which the task should be executed. |
|
Purpose: Schedule a task to run at a specific future time. |
|
Note: Distant `eta` times are not recommended; prefer periodic tasks for such cases. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Configure Celery Beat Crontab Schedule in Python |
|
DESCRIPTION: This Python code demonstrates how to configure a periodic task using `celery.schedules.crontab` within the `app.conf.beat_schedule` dictionary. It provides an example of scheduling a task to run every Monday morning at 7:30 a.m. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/periodic-tasks.rst#_snippet_6 |
|
|
|
LANGUAGE: Python |
|
CODE: |
|
``` |
|
from celery.schedules import crontab |
|
|
|
app.conf.beat_schedule = { |
|
# Executes every Monday morning at 7:30 a.m. |
|
'add-every-monday-morning': { |
|
'task': 'tasks.add', |
|
'schedule': crontab(hour=7, minute=30, day_of_week=1), |
|
'args': (16, 16), |
|
}, |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Celery Beat Scheduler Setting |
|
DESCRIPTION: The `beat_scheduler` setting specifies the default scheduler class for Celery Beat. It defaults to `"celery.beat:PersistentScheduler"` but can be set to other schedulers like `"django_celery_beat.schedulers:DatabaseScheduler"` for extensions. It can also be configured via the `celery beat -S` argument. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/configuration.rst#_snippet_194 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
beat_scheduler: |
|
Default: "celery.beat:PersistentScheduler" |
|
Description: The default scheduler class. May be set to `django_celery_beat.schedulers:DatabaseScheduler` or via `celery beat -S` argument. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Define Celery Periodic Tasks with Crontab Schedules |
|
DESCRIPTION: This snippet demonstrates how to define periodic tasks in Celery using the `@periodic_task` decorator and `crontab` for scheduling. It shows examples for daily, weekly (Monday), and hourly execution intervals. These tasks run automatically based on the specified schedule. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/history/changelog-1.0.rst#_snippet_3 |
|
|
|
LANGUAGE: Python |
|
CODE: |
|
``` |
|
@periodic_task(run_every=crontab(hour=7, minute=30)) |
|
def every_morning(): |
|
print('Runs every morning at 7:30a.m') |
|
|
|
@periodic_task(run_every=crontab(hour=7, minute=30, day_of_week='mon')) |
|
def every_monday_morning(): |
|
print('Run every monday morning at 7:30a.m') |
|
|
|
@periodic_task(run_every=crontab(minutes=30)) |
|
def every_hour(): |
|
print('Runs every hour on the clock (e.g., 1:30, 2:30, 3:30 etc.).') |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Celery Crontab Schedule Examples |
|
DESCRIPTION: Examples demonstrating various `crontab` expressions for scheduling tasks in Celery, covering minute, hour, day of month, and month of year specifications. Each example shows a `crontab` configuration and its corresponding execution logic. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/periodic-tasks.rst#_snippet_8 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
crontab(minute=0, hour='*/5') |
|
Execute hour divisible by 5. This means that it is triggered at 3pm, not 5pm (since 3pm equals the 24-hour clock value of "15", which is divisible by 5). |
|
``` |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
crontab(minute=0, hour='*/3,8-17') |
|
Execute every hour divisible by 3, and every hour during office hours (8am-5pm). |
|
``` |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
crontab(0, 0, day_of_month='2') |
|
Execute on the second day of every month. |
|
``` |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
crontab(0, 0, |
|
day_of_month='2-30/2') |
|
Execute on every even numbered day. |
|
``` |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
crontab(0, 0, |
|
day_of_month='1-7,15-21') |
|
Execute on the first and third weeks of the month. |
|
``` |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
crontab(0, 0, day_of_month='11', |
|
month_of_year='5') |
|
Execute on the eleventh of May every year. |
|
``` |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
crontab(0, 0, |
|
month_of_year='*/3') |
|
Execute every day on the first month of every quarter. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Celery Beat Entry Fields Reference |
|
DESCRIPTION: This section describes the available configuration fields for a Celery beat schedule entry. These fields define the task to execute, its schedule, and any arguments or execution options. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/periodic-tasks.rst#_snippet_5 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
task: |
|
Type: string |
|
Description: The name of the task to execute. Not the import path. |
|
schedule: |
|
Type: integer (seconds), datetime.timedelta, celery.schedules.crontab, or custom schedule type |
|
Description: The frequency of execution. |
|
args: |
|
Type: list or tuple |
|
Description: Positional arguments for the task. |
|
kwargs: |
|
Type: dict |
|
Description: Keyword arguments for the task. |
|
options: |
|
Type: dict |
|
Description: Execution options, such as 'exchange', 'routing_key', 'expires', supported by Task.apply_async. |
|
relative: |
|
Type: boolean |
|
Description: If true, datetime.timedelta schedules are rounded to the nearest second, minute, hour, or day. Defaults to false, meaning frequency is relative to celery beat start time. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Customize Periodic Task Schedule at Runtime |
|
DESCRIPTION: Demonstrates how to change the interval of a periodic task at runtime by subclassing `celery.schedules.schedule` and overriding its `is_due` method. This allows for dynamic scheduling logic beyond fixed intervals. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/faq.rst#_snippet_17 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
from celery.schedules import schedule |
|
|
|
class my_schedule(schedule): |
|
|
|
def is_due(self, last_run_at): |
|
return run_now, next_time_to_check |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Celery Beat Schedule Filename Setting |
|
DESCRIPTION: The `beat_schedule_filename` setting defines the name of the file used by `PersistentScheduler` to store periodic task run times. It defaults to `"celerybeat-schedule"`. The suffix `.db` may be appended. It can also be set via the `celery beat --schedule` argument. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/configuration.rst#_snippet_195 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
beat_schedule_filename: |
|
Default: "celerybeat-schedule" |
|
Description: Name of the file used by `PersistentScheduler` to store the last run times of periodic tasks. Suffix `.db` may be appended. Can be set via `celery beat --schedule` argument. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Schedule `starmap` execution asynchronously in Celery |
|
DESCRIPTION: Shows how to schedule a `starmap` operation to run after a specified delay using `apply_async` with a `countdown`. This demonstrates that `map` and `starmap` are signature objects. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/canvas.rst#_snippet_75 |
|
|
|
LANGUAGE: pycon |
|
CODE: |
|
``` |
|
>>> add.starmap(zip(range(10), range(10))).apply_async(countdown=10) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Configure Custom Celery Beat Schedule File Location |
|
DESCRIPTION: Command to start Celery Beat and specify a custom path for its schedule database file. This is useful when the default celerybeat-schedule file cannot be written to the current directory, allowing for explicit control over its storage location. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/periodic-tasks.rst#_snippet_15 |
|
|
|
LANGUAGE: console |
|
CODE: |
|
``` |
|
celery -A proj beat -s /home/celery/var/run/celerybeat-schedule |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Configure Celerybeat Scheduler in Python |
|
DESCRIPTION: This snippet demonstrates how to set the `CELERYBEAT_SCHEDULER` configuration option in Celery. This setting defines the default scheduler class used by `celerybeat`, allowing users to specify custom or database-backed schedulers. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/history/changelog-2.1.rst#_snippet_0 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler' |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Inspect Scheduled Celery Tasks |
|
DESCRIPTION: Displays tasks that have been reserved by workers due to an `eta` or `countdown` argument. These tasks are scheduled for future execution. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/monitoring.rst#_snippet_8 |
|
|
|
LANGUAGE: console |
|
CODE: |
|
``` |
|
$ celery -A proj inspect scheduled |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Celery Solar Schedule Event Types |
|
DESCRIPTION: Defines the various astronomical and civil event types that can be used with Celery's `solar` schedule, such as `dawn_astronomical`, `dawn_nautical`, and `dawn_civil`, along with their precise astronomical definitions. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/periodic-tasks.rst#_snippet_11 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
Event Types: |
|
dawn_astronomical: Execute at the moment after which the sky is no longer completely dark. This is when the sun is 18 degrees below the horizon. |
|
dawn_nautical: Execute when there's enough sunlight for the horizon and some objects to be distinguishable; formally, when the sun is 12 degrees below the horizon. |
|
dawn_civil: Execute when there's enough light for |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Schedule Celery Task with `eta` for Precise Future Execution |
|
DESCRIPTION: This snippet illustrates how to schedule a Celery task to run at a specific future date and time using the `eta` argument. It requires a `datetime.datetime` object, preferably with timezone information, to define the exact execution time. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/calling.rst#_snippet_13 |
|
|
|
LANGUAGE: pycon |
|
CODE: |
|
``` |
|
>>> from datetime import datetime, timedelta, timezone |
|
|
|
>>> tomorrow = datetime.now(timezone.utc) + timedelta(days=1) |
|
>>> add.apply_async((2, 2), eta=tomorrow) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Celery Task Scheduling with apply_async (Python) |
|
DESCRIPTION: Demonstrates how to schedule Celery tasks using `apply_async` with `countdown` for delayed execution and `eta` for execution at a specific future datetime. This method provides advanced control over task scheduling. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/history/changelog-1.0.rst#_snippet_48 |
|
|
|
LANGUAGE: Python |
|
CODE: |
|
``` |
|
# Run 10 seconds into the future. |
|
res = apply_async(MyTask, countdown=10); |
|
|
|
# Run 1 day from now |
|
res = apply_async(MyTask, |
|
eta=datetime.now() + timedelta(days=1)) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Configure Celery Periodic Tasks via beat_schedule Setting |
|
DESCRIPTION: This Python snippet illustrates how to define periodic tasks directly within the `app.conf.beat_schedule` dictionary. This method allows for manual configuration of task names, target tasks, schedules, and arguments. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/periodic-tasks.rst#_snippet_4 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
app.conf.beat_schedule = { |
|
'add-every-30-seconds': { |
|
'task': 'tasks.add', |
|
'schedule': 30.0, |
|
'args': (16, 16) |
|
} |
|
} |
|
app.conf.timezone = 'UTC' |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Dump Scheduled (ETA) Tasks on Celery Worker (Python) |
|
DESCRIPTION: Illustrates how to retrieve tasks waiting to be scheduled with an ETA or countdown using the `i.scheduled()` method. This helps monitor tasks that are set to run at a future time. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/workers.rst#_snippet_33 |
|
|
|
LANGUAGE: pycon |
|
CODE: |
|
``` |
|
>>> i.scheduled() |
|
[{'worker1.example.com': |
|
[{'eta': '2010-06-07 09:07:52', 'priority': 0, |
|
'request': { |
|
'name': 'tasks.sleeptask', |
|
'id': '1a7980ea-8b19-413e-91d2-0b74f3844c4d', |
|
'args': '[1]', |
|
'kwargs': '{}'}}, |
|
{'eta': '2010-06-07 09:07:53', 'priority': 0, |
|
'request': { |
|
'name': 'tasks.sleeptask', |
|
'id': '49661b9a-aa22-4120-94b7-9ee8031d219d', |
|
'args': '[2]', |
|
'kwargs': '{}'}}]}] |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Django Celery Beat Database Schema |
|
DESCRIPTION: This API documentation outlines the database tables created by `django-celery-beat` when using a database-backed schedule. These tables, including `PeriodicTask`, `IntervalSchedule`, `CrontabSchedule`, and `PeriodicTasks`, are essential for managing and storing periodic task definitions and their schedules. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/faq.rst#_snippet_24 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
django-celery-beat Database Tables: |
|
- PeriodicTask: Stores definitions of periodic tasks. |
|
- IntervalSchedule: Defines schedules based on time intervals. |
|
- CrontabSchedule: Defines schedules based on crontab expressions. |
|
- PeriodicTasks: Helper table for managing periodic tasks. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Celery Solar Schedule Function Arguments |
|
DESCRIPTION: Documentation for the `solar(event, latitude, longitude)` function, detailing the meaning of positive and negative signs for latitude and longitude when specifying geographical coordinates. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/periodic-tasks.rst#_snippet_10 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
solar(event, latitude, longitude) |
|
Arguments: |
|
latitude: |
|
+: North |
|
-: South |
|
longitude: |
|
+: East |
|
-: West |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: APIDOC: Celery Remote Control and Beat Scheduler Updates |
|
DESCRIPTION: Describes new remote control commands for worker configuration and stats, and an update to the beat scheduler to use a customizable `now()` method for schedules. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/history/changelog-3.0.rst#_snippet_22 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
Stats Broadcast Command: Now includes the workers pid. |
|
Conf Remote Control Command: New command to get a worker's current configuration. |
|
Chord Unlock Task: Ability to modify the chord unlock task's countdown argument (Issue #1146). |
|
Beat Scheduler: Now uses the `now()` method of the schedule, allowing custom date/time provision. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Start Celery Beat Service |
|
DESCRIPTION: Command to start the Celery Beat service, which is responsible for scheduling periodic tasks. It requires specifying the Celery application module. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/periodic-tasks.rst#_snippet_13 |
|
|
|
LANGUAGE: console |
|
CODE: |
|
``` |
|
celery -A proj beat |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Python: Crontab Expressions for Periodic Tasks |
|
DESCRIPTION: These Python console snippets demonstrate how to define crontab expressions for periodic tasks. The first shows a simple 'every 15 minutes' schedule, while the second illustrates a more complex schedule for specific hours and days of the week. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/history/changelog-2.0.rst#_snippet_22 |
|
|
|
LANGUAGE: pycon |
|
CODE: |
|
``` |
|
>>> crontab(minute='*/15') |
|
``` |
|
|
|
LANGUAGE: pycon |
|
CODE: |
|
``` |
|
>>> crontab(minute='*/30', hour='8-17,1-2', day_of_week='thu-fri') |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Start Celerybeat Scheduler |
|
DESCRIPTION: Command to launch the `celerybeat` daemon, which is responsible for scheduling periodic tasks. It's crucial to run this on only one server to avoid duplicate execution of periodic tasks, as the periodic task system has been centralized. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/history/changelog-1.0.rst#_snippet_33 |
|
|
|
LANGUAGE: Console |
|
CODE: |
|
``` |
|
$ celerybeat |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Beat Hanging After First Schedule Iteration Fix |
|
DESCRIPTION: Resolves a problem where Celery Beat would hang after its first schedule iteration. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/history/changelog-3.1.rst#_snippet_53 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
Component: Beat |
|
Issue: Hanging after first schedule iteration |
|
Status: Fixed. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Import Crontab and Periodic Task for Celery Scheduling |
|
DESCRIPTION: Example Python code demonstrating the necessary imports for implementing crontab-like scheduling with Celery's periodic tasks. It imports `crontab` from `celery.schedules` and `periodic_task` from `celery.decorators`. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/history/changelog-1.0.rst#_snippet_2 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
from celery.schedules import crontab |
|
from celery.decorators import periodic_task |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Timer.call_after Method API |
|
DESCRIPTION: Documents the `timer.call_after` method, which schedules a given callback function to be executed after a specified number of seconds, optionally with arguments. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/extending.rst#_snippet_41 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
timer.call_after(secs, callback, args=(), kwargs=()): |
|
secs: Delay in seconds before the callback is executed. |
|
callback: The function to call. |
|
args: Positional arguments to pass to the callback. |
|
kwargs: Keyword arguments to pass to the callback. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Schedule Celery Task with `countdown` for Delayed Execution |
|
DESCRIPTION: This example demonstrates using the `countdown` argument with `apply_async` to delay a task's execution by a specified number of seconds. The `result.get()` call will block until the countdown expires and the task completes. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/calling.rst#_snippet_12 |
|
|
|
LANGUAGE: pycon |
|
CODE: |
|
``` |
|
>>> result = add.apply_async((2, 2), countdown=3) |
|
>>> result.get() # this takes at least 3 seconds to return |
|
4 |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Update Deprecated Celery Schedule Import |
|
DESCRIPTION: Demonstrates how to replace the deprecated `celery.task.schedules` import with the new `celery.schedules` module for `crontab` and other schedule-related functionalities, reflecting a change in module organization. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/history/changelog-2.2.rst#_snippet_29 |
|
|
|
LANGUAGE: Python |
|
CODE: |
|
``` |
|
# Old (deprecated) |
|
from celery.task.schedules import crontab |
|
|
|
# New (recommended) |
|
from celery.schedules import crontab |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Schedule Error Handlers for Non-Registered Tasks in Celery |
|
DESCRIPTION: This Python code demonstrates how to schedule error handlers that are not registered tasks in the current worker. It uses `celery.Signature` to define a task 'bar' and links an error handler 'msg.err' to it, which will be sent to the 'msg' queue upon failure, allowing for flexible error handling. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/history/changelog-4.3.rst#_snippet_0 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
from celery import Signature |
|
Signature( |
|
'bar', args=['foo'], |
|
link_error=Signature('msg.err', queue='msg') |
|
).apply_async() |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Celery Worker Setting: Timer Precision |
|
DESCRIPTION: Sets the maximum time (in seconds) the ETA scheduler can sleep before rechecking the schedule. A lower value increases precision but may consume more resources. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/configuration.rst#_snippet_146 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
Setting: worker_timer_precision |
|
Default: 1.0 seconds |
|
Description: Set the maximum time in seconds that the ETA scheduler can sleep between rechecking the schedule. If you need near millisecond precision you can set this to 0.1. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Schedule Unregistered Error Handlers with Celery Signature |
|
DESCRIPTION: This Python code demonstrates how to schedule an error handler that is not a registered task within the current worker using Celery's Signature. It shows linking a separate Signature instance, 'msg.err', to the `link_error` parameter of the main task's Signature, allowing for flexible error handling and routing to a specific queue. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/history/changelog-4.4.rst#_snippet_0 |
|
|
|
LANGUAGE: Python |
|
CODE: |
|
``` |
|
from celery import Signature |
|
Signature( |
|
'bar', args=['foo'], |
|
link_error=Signature('msg.err', queue='msg') |
|
).apply_async() |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Celery Beat Solar Event Triggers |
|
DESCRIPTION: Defines various solar events that can be used as triggers for scheduled tasks in Celery Beat. Each event specifies a precise moment relative to the sun's position, such as sunrise, sunset, and different stages of twilight. These events are calculated in UTC and are designed to handle polar regions. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/periodic-tasks.rst#_snippet_12 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
Event: dawn_astronomical |
|
Description: Execute at the moment when the sky begins to lighten; formally, when the Sun is 18 degrees below the horizon. |
|
|
|
Event: dawn_nautical |
|
Description: Execute when the sun is 12 degrees below the horizon. The horizon becomes visible, and objects are distinguishable. |
|
|
|
Event: dawn_civil |
|
Description: Execute at the beginning of civil twilight, when objects to be distinguishable so that outdoor activities can commence; formally, when the Sun is 6 degrees below the horizon. |
|
|
|
Event: sunrise |
|
Description: Execute when the upper edge of the sun appears over the eastern horizon in the morning. |
|
|
|
Event: solar_noon |
|
Description: Execute when the sun is highest above the horizon on that day. |
|
|
|
Event: sunset |
|
Description: Execute when the trailing edge of the sun disappears over the western horizon in the evening. |
|
|
|
Event: dusk_civil |
|
Description: Execute at the end of civil twilight, when objects are still distinguishable and some stars and planets are visible. Formally, when the sun is 6 degrees below the horizon. |
|
|
|
Event: dusk_nautical |
|
Description: Execute when the sun is 12 degrees below the horizon. Objects are no longer distinguishable, and the horizon is no longer visible to the naked eye. |
|
|
|
Event: dusk_astronomical |
|
Description: Execute at the moment after which the sky becomes completely dark; formally, when the sun is 18 degrees below the horizon. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Define Celery Periodic Tasks using on_after_configure Signal |
|
DESCRIPTION: This Python example shows how to define periodic tasks using the `on_after_configure` signal. It demonstrates adding tasks with fixed intervals and cron-like schedules, ensuring tasks are registered after the Celery app is fully set up. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/periodic-tasks.rst#_snippet_3 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
from celery import Celery |
|
from celery.schedules import crontab |
|
|
|
app = Celery() |
|
|
|
@app.on_after_configure.connect |
|
def setup_periodic_tasks(sender: Celery, **kwargs): |
|
# Calls test('hello') every 10 seconds. |
|
sender.add_periodic_task(10.0, test.s('hello'), name='add every 10') |
|
|
|
# Calls test('hello') every 30 seconds. |
|
# It uses the same signature of previous task, an explicit name is |
|
# defined to avoid this task replacing the previous one defined. |
|
sender.add_periodic_task(30.0, test.s('hello'), name='add every 30') |
|
|
|
# Calls test('world') every 30 seconds |
|
sender.add_periodic_task(30.0, test.s('world'), expires=10) |
|
|
|
# Executes every Monday morning at 7:30 a.m. |
|
sender.add_periodic_task( |
|
crontab(hour=7, minute=30, day_of_week=1), |
|
test.s('Happy Mondays!'), |
|
) |
|
|
|
@app.task |
|
def test(arg): |
|
print(arg) |
|
|
|
@app.task |
|
def add(x, y): |
|
z = x + y |
|
print(z) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Celery Beat Module API Reference |
|
DESCRIPTION: This entry provides a reference to the `celery.beat` module, indicating that its full API, including all public and undocumented members, is documented. The module is central to Celery's periodic task scheduling. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/reference/celery.beat.rst#_snippet_0 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
Module: celery.beat |
|
Description: The celery.beat module provides a scheduler that periodically executes Celery tasks. |
|
Members: All public members of the celery.beat module. |
|
Undocumented Members: All undocumented members of the celery.beat module. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Celery Beat: beat_max_loop_interval Setting |
|
DESCRIPTION: Configures the maximum number of seconds Celery Beat can sleep between checking the schedule. The default value is 0, which is scheduler-specific; for the default Celery scheduler, it's 300 seconds (5 minutes), while for django-celery-beat, it's 5 seconds. When running embedded on Jython, it's overridden to 1 second for timely shutdown. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/configuration.rst#_snippet_197 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
Setting: beat_max_loop_interval |
|
Default: 0 (scheduler specific, e.g., 300s for default Celery, 5s for django-celery-beat) |
|
Description: The maximum number of seconds celery.bin.beat can sleep between checking the schedule. |
|
Note: Overridden to 1s on Jython when embedded for timely shutdown. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Improvement: celerybeat PersistentScheduler handles corrupted files |
|
DESCRIPTION: The `PersistentScheduler` in `celerybeat` now includes logic to automatically remove corrupted schedule files, enhancing robustness (Issue #346). |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/history/changelog-2.2.rst#_snippet_12 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
celerybeat: PersistentScheduler |
|
Behavior: Automatically removes corrupted schedule files (Issue #346). |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Celery Beat: beat_cron_starting_deadline Setting |
|
DESCRIPTION: Specifies the number of seconds Celery Beat can look back when determining if a cron schedule is due. If set to None, cron jobs that are past due will always run immediately. Setting this value higher than 3600 seconds (1 hour) is strongly discouraged. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/configuration.rst#_snippet_198 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
Setting: beat_cron_starting_deadline |
|
Version Added: 5.3 |
|
Default: None |
|
Description: When using cron, the number of seconds celery.bin.beat can look back when deciding whether a cron schedule is due. |
|
Note: If set to None, past due cronjobs always run immediately. Setting higher than 3600s (1 hour) is highly discouraged. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Celery Setting: beat_cron_starting_deadline |
|
DESCRIPTION: API documentation for the `beat_cron_starting_deadline` setting. This setting controls how far back `celery beat` can look when determining if a cron schedule is due. Setting it to `None` ensures past due cronjobs run immediately. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/history/whatsnew-5.3.rst#_snippet_4 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
Setting: beat_cron_starting_deadline |
|
Type: int or None |
|
Description: Number of seconds `celery beat` can look back for cron schedules. |
|
Behavior: If None, past due cronjobs run immediately. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Celery Signal Handling: SIGTERM and SIGINT |
|
DESCRIPTION: Documents that `celerybeat` now gracefully handles `SIGTERM` and `SIGINT` signals by syncing the schedule to disk. This ensures that the schedule is persisted during shutdown, preventing data loss. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/history/changelog-1.0.rst#_snippet_26 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
SIGTERM |
|
Description: Signal for graceful termination. Handled by celerybeat to sync schedule to disk. |
|
|
|
SIGINT |
|
Description: Signal for interrupt. Handled by celerybeat to sync schedule to disk. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Embedded Beat App Context Fix |
|
DESCRIPTION: Ensures that the embedded beat scheduler properly sets the application context for its threads and processes, preventing potential context-related issues. (Issue #2594). |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/history/changelog-3.1.rst#_snippet_5 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
Component: Worker (Embedded Beat) |
|
Issue: #2594 |
|
Description: Embedded beat now properly sets app for thread/process. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Celery Timer Module API Reference |
|
DESCRIPTION: Detailed API documentation for the `timer` module in Celery, outlining methods for scheduling callbacks based on time delays, repetitions, or specific timestamps. These methods are fundamental for managing asynchronous task execution within the Celery ecosystem. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/extending.rst#_snippet_42 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
Module: timer |
|
|
|
Method: call_after |
|
Signature: timer.call_after(secs, callback, args=(), kwargs=(), priority=0) |
|
Description: Schedules a callback to be executed once after a specified number of seconds. |
|
Parameters: |
|
secs (int/float): The delay in seconds before the callback is executed. |
|
callback (callable): The function or callable to execute. |
|
args (tuple, optional): Positional arguments to pass to the callback. Defaults to an empty tuple. |
|
kwargs (dict, optional): Keyword arguments to pass to the callback. Defaults to an empty dictionary. |
|
priority (int, optional): The priority level for the scheduled task. Defaults to 0. |
|
|
|
Method: call_repeatedly |
|
Signature: timer.call_repeatedly(secs, callback, args=(), kwargs=(), priority=0) |
|
Description: Schedules a callback to be executed repeatedly at a specified interval. |
|
Parameters: |
|
secs (int/float): The interval in seconds between each execution of the callback. |
|
callback (callable): The function or callable to execute. |
|
args (tuple, optional): Positional arguments to pass to the callback. Defaults to an empty tuple. |
|
kwargs (dict, optional): Keyword arguments to pass to the callback. Defaults to an empty dictionary. |
|
priority (int, optional): The priority level for the scheduled task. Defaults to 0. |
|
|
|
Method: call_at |
|
Signature: timer.call_at(eta, callback, args=(), kwargs=(), priority=0) |
|
Description: Schedules a callback to be executed at a specific future time. |
|
Parameters: |
|
eta (datetime): The exact time (datetime object) when the callback should be executed. |
|
callback (callable): The function or callable to execute. |
|
args (tuple, optional): Positional arguments to pass to the callback. Defaults to an empty tuple. |
|
kwargs (dict, optional): Keyword arguments to pass to the callback. Defaults to an empty dictionary. |
|
priority (int, optional): The priority level for the scheduled task. Defaults to 0. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: `celerybeat` Reuses Connection for Large Task Sets |
|
DESCRIPTION: The `celerybeat` scheduler now reuses the same connection when publishing large sets of tasks. This optimization improves performance and reduces overhead by minimizing connection establishment. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/history/changelog-1.0.rst#_snippet_7 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
``celerybeat``: Now reuses the same connection when publishing large sets of tasks. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Schedule Celery Task After Django Transaction Commit |
|
DESCRIPTION: This Python snippet demonstrates how to use Django's `transaction.on_commit` to defer the execution of a Celery task until after a database transaction has been successfully committed. This pattern ensures that tasks related to model changes are only processed if the transaction is not rolled back, maintaining data integrity. It shows an example of creating an article and then scheduling a notification task. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/history/whatsnew-4.0.rst#_snippet_0 |
|
|
|
LANGUAGE: Python |
|
CODE: |
|
``` |
|
from functools import partial |
|
from django.db import transaction |
|
|
|
from .models import Article, Log |
|
from .tasks import send_article_created_notification |
|
|
|
def create_article(request): |
|
with transaction.atomic(): |
|
article = Article.objects.create(**request.POST) |
|
# send this task only if the rest of the transaction succeeds. |
|
transaction.on_commit(partial( |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Celery Task Expiration with apply_async |
|
DESCRIPTION: This snippet demonstrates how to schedule a Celery task (`add`) to expire after a specified duration using `apply_async`. The `expires` argument sets the task's expiration time, after which it will be marked as REVOKED if not processed. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/calling.rst#_snippet_17 |
|
|
|
LANGUAGE: pycon |
|
CODE: |
|
``` |
|
add.apply_async((10, 10), kwargs, |
|
expires=datetime.now(timezone.utc) + timedelta(days=1)) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Create Celery Chain with Pipe Operator |
|
DESCRIPTION: Demonstrates an alternative, more concise syntax for creating a Celery task chain using the `|` (pipe) operator. The `apply_async()` method schedules the chain for asynchronous execution. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/canvas.rst#_snippet_44 |
|
|
|
LANGUAGE: pycon |
|
CODE: |
|
``` |
|
>>> (add.s(2, 2) | mul.s(8) | mul.s(10)).apply_async() |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Celery Worker Prefork Pool Configuration Options |
|
DESCRIPTION: Documents command-line options and settings for configuring the Celery worker's prefork pool behavior, including scheduling strategy and memory limits. It explains the `-Ofair` and `-Ofast` options for task scheduling and the `--max-memory-per-child` option/setting for memory management. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/history/whatsnew-4.0.rst#_snippet_20 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
Command-line Option: -Ofair |
|
Description: Default scheduling strategy for prefork pool. Ensures no task is sent to a child process already executing a task. |
|
Note: May perform slightly worse for only short-running tasks. |
|
|
|
Command-line Option: -Ofast |
|
Description: Re-enables the default scheduling behavior from Celery 3.1 (tasks sent to first writable inqueue, round-robin). |
|
|
|
Command-line Option: --max-memory-per-child <kilobytes> |
|
Description: Limits the maximum amount of resident memory (RSS) allocated per prefork pool child process. |
|
Unit: Kilobytes. |
|
Behavior: A child process exceeding the limit is terminated and replaced after its current task completes. |
|
|
|
Setting: worker_max_memory_per_child |
|
Description: Configuration setting equivalent to --max-memory-per-child. |
|
|
|
Log File Format Option: %I |
|
Description: Used in init-scripts and 'celery multi' to ensure each child process has a separate log file (e.g., /var/log/celery/%n%I.log). |
|
Program: celery multi |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Execute Celery Task Signature with .apply_async() |
|
DESCRIPTION: Shows how to use `apply_async` with a task signature, providing arguments, keyword arguments, and execution options. This method offers fine-grained control over task execution, including scheduling and routing. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/canvas.rst#_snippet_7 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
add.apply_async(args, kwargs, **options) |
|
add.signature(args, kwargs, **options).apply_async() |
|
|
|
add.apply_async((2, 2), countdown=1) |
|
add.signature((2, 2), countdown=1).apply_async() |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Reset Django-Celery-Beat Periodic Tasks (Modern) |
|
DESCRIPTION: For Celery 4.0 and above, using `django-celery-beat`, this console command resets the `last_run_at` field for `PeriodicTask` objects. This is crucial when timezone settings change and the scheduler doesn't automatically reset. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/periodic-tasks.rst#_snippet_2 |
|
|
|
LANGUAGE: console |
|
CODE: |
|
``` |
|
$ python manage.py shell |
|
>>> from django_celery_beat.models import PeriodicTask |
|
>>> PeriodicTask.objects.update(last_run_at=None) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Define Worker Bootstep Requiring Timer Component |
|
DESCRIPTION: Example of a Celery worker bootstep that requires the `Timer` component. This allows the bootstep to schedule functions using the worker's timer. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/extending.rst#_snippet_6 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
class WorkerStep(bootsteps.StartStopStep): |
|
requires = {'celery.worker.components:Timer'} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Celery Beat: `celery.beat.Scheduler.schedules_equal` Handles `None` Arguments |
|
DESCRIPTION: The `schedules_equal` method within `celery.beat.Scheduler` has been updated to gracefully handle cases where one or both of its input arguments are `None`. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/history/changelog-4.3.rst#_snippet_8 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
Method Behavior Update: |
|
Method: celery.beat.Scheduler.schedules_equal |
|
Signature: schedules_equal(self, schedule1, schedule2) |
|
New Behavior: Accepts `None` for `schedule1` or `schedule2`. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Implement Deadlock Detection Bootstep Using Worker Timer |
|
DESCRIPTION: An example bootstep that uses the worker's timer to periodically check for deadlocked requests. It requires the `Timer` component and demonstrates `call_repeatedly` for scheduled tasks and proper cleanup in `stop`. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/extending.rst#_snippet_11 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
from celery import bootsteps |
|
|
|
|
|
class DeadlockDetection(bootsteps.StartStopStep): |
|
requires = {'celery.worker.components:Timer'} |
|
|
|
def __init__(self, worker, deadlock_timeout=3600): |
|
self.timeout = deadlock_timeout |
|
self.requests = [] |
|
self.tref = None |
|
|
|
def start(self, worker): |
|
# run every 30 seconds. |
|
self.tref = worker.timer.call_repeatedly( |
|
30.0, self.detect, (worker,), priority=10, |
|
) |
|
|
|
def stop(self, worker): |
|
if self.tref: |
|
self.tref.cancel() |
|
self.tref = None |
|
|
|
def detect(self, worker): |
|
# update active requests |
|
for req in worker.active_requests: |
|
if req.time_start and time() - req.time_start > self.timeout: |
|
raise SystemExit() |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Celery Worker Timer Setting |
|
DESCRIPTION: The `worker_timer` setting defines the name of the ETA scheduler class used by the worker. It defaults to `"kombu.asynchronous.hub.timer:Timer"` or is set by the pool implementation. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/configuration.rst#_snippet_186 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
worker_timer: |
|
Default: "kombu.asynchronous.hub.timer:Timer" |
|
Description: Name of the ETA scheduler class used by the worker. Default is or set by the pool implementation. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Reset Django-Celery Periodic Tasks (Legacy) |
|
DESCRIPTION: For older Django-Celery versions (4.0 and below), this console command resets the `last_run_at` field for `PeriodicTask` objects. This is necessary when timezone settings change and the scheduler doesn't automatically reset. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/periodic-tasks.rst#_snippet_1 |
|
|
|
LANGUAGE: console |
|
CODE: |
|
``` |
|
$ python manage.py shell |
|
>>> from djcelery.models import PeriodicTask |
|
>>> PeriodicTask.objects.update(last_run_at=None) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Celery Signal: beat_init |
|
DESCRIPTION: The `beat_init` signal is dispatched whenever the `celerybeat` scheduler starts, regardless of whether it's running as a standalone process or embedded within another application. The sender of this signal is always an instance of `celery.beat.Service`. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/history/changelog-2.2.rst#_snippet_41 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
celery.signals.beat_init: |
|
Description: Dispatched when celerybeat starts (standalone or embedded). |
|
Sender: celery.beat.Service instance. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Celery Consumer Methods API |
|
DESCRIPTION: This section documents key methods available on the Celery consumer object, including functionalities for resetting rate limits, creating task buckets, and managing task queues for consumption. It also covers scheduling ETA tasks. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/extending.rst#_snippet_24 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
consumer.reset_rate_limits() |
|
Updates the ``task_buckets`` mapping for all registered task types. |
|
|
|
consumer.bucket_for_task(type, Bucket=TokenBucket) |
|
Creates rate limit bucket for a task using its ``task.rate_limit`` attribute. |
|
|
|
consumer.add_task_queue(name, exchange=None, exchange_type=None, |
|
routing_key=None, \*\*options): |
|
Adds new queue to consume from. This will persist on connection restart. |
|
|
|
consumer.cancel_task_queue(name) |
|
Stop consuming from queue by name. This will persist on connection |
|
restart. |
|
|
|
apply_eta_task(request) |
|
Schedule ETA task to execute based on the ``request.eta`` attribute. |
|
(:class:`~celery.worker.request.Request`) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: APIDOC: Timezone Information in `eta` and `expires` |
|
DESCRIPTION: This change indicates that the task message `eta` and `expires` fields now include timezone information. This enhancement ensures more accurate and reliable scheduling and expiry handling across different timezones. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/history/whatsnew-3.1.rst#_snippet_46 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
Task Fields: eta, expires |
|
Description: Now include timezone information. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Embed Celerybeat in Celeryd Worker |
|
DESCRIPTION: Command to embed the `celerybeat` scheduler directly within the `celeryd` worker process. This is useful for setups with only a single worker server, eliminating the need to run `celerybeat` as a separate daemon. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/history/changelog-1.0.rst#_snippet_34 |
|
|
|
LANGUAGE: Console |
|
CODE: |
|
``` |
|
$ celeryd --beat # Embed celerybeat in celeryd. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Start Celery beat service with Django DatabaseScheduler |
|
DESCRIPTION: Launches the Celery beat service, specifying the DatabaseScheduler from django-celery-beat to manage and execute periodic tasks defined in the Django database. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/periodic-tasks.rst#_snippet_19 |
|
|
|
LANGUAGE: Shell |
|
CODE: |
|
``` |
|
$ celery -A proj beat -l INFO --scheduler django_celery_beat.schedulers:DatabaseScheduler |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Configure Celery Beat Timezone in Python |
|
DESCRIPTION: This snippet demonstrates how to set the timezone for Celery Beat using the `timezone` setting. This can be done directly on the app configuration or via a configuration module. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/periodic-tasks.rst#_snippet_0 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
timezone = 'Europe/London' |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Configure Event Queue Message TTL |
|
DESCRIPTION: Sets the message expiry time for messages sent to a monitor client's event queue. Messages are deleted after this duration. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/configuration.rst#_snippet_154 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
Setting: event_queue_ttl |
|
Transports Supported: amqp |
|
Default: 5.0 seconds |
|
Description: Message expiry time in seconds (int/float) for when messages sent to a monitor clients event queue is deleted (x-message-ttl). For example, if this value is set to 10 then a message delivered to this queue will be deleted after 10 seconds. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Celery Task Request Object Attributes |
|
DESCRIPTION: Documents the various attributes available on the `self.request` object within a Celery task, providing metadata about the task's execution environment, scheduling, and message delivery. These attributes offer insights into how the task was invoked and its current state. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/tasks.rst#_snippet_15 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
Task Request Attributes: |
|
is_eager: bool - Set to True if the task is executed locally in the client, not by a worker. |
|
eta: datetime.datetime (UTC) - The original ETA of the task (if any). This is in UTC time (depending on the enable_utc setting). |
|
expires: datetime.datetime (UTC) - The original expiry time of the task (if any). This is in UTC time (depending on the enable_utc setting). |
|
hostname: str - Node name of the worker instance executing the task. |
|
delivery_info: dict - Additional message delivery information. This is a mapping containing the exchange and routing key used to deliver this task. Used by for example Task.retry() to resend the task to the same destination queue. Availability of keys in this dict depends on the message broker used. |
|
reply-to: str - Name of queue to send replies back to (used with RPC result backend for example). |
|
called_directly: bool - This flag is set to true if the task wasn't executed by the worker. |
|
timelimit: tuple[soft_limit: int | None, hard_limit: int | None] - A tuple of the current (soft, hard) time limits active for this task (if any). |
|
callbacks: list[Signature] - A list of signatures to be called if this task returns successfully. |
|
errbacks: list[Signature] - A list of signatures to be called if this task fails. |
|
utc: bool - Set to true the caller has UTC enabled (enable_utc setting). |
|
headers: dict | None - Mapping of message headers sent with this task message (may be None). (versionadded 3.1) |
|
reply_to: str - Where to send reply to (queue name). (versionadded 3.1) |
|
correlation_id: str - Usually the same as the task id, often used in AMQP to keep track of what a reply is for. (versionadded 3.1) |
|
root_id: str | None - The unique id of the first task in the workflow this task is part of (if any). (versionadded 4.0) |
|
parent_id: str | None - The unique id of the task that called this task (if any). (versionadded 4.0) |
|
chain: list[Task] - Reversed list of tasks that form a chain (if any). The last item in this list will be the next task to succeed the current task. If using version one of the task protocol the chain tasks will be in request.callbacks instead. (versionadded 4.0) |
|
properties: dict | None - Mapping of message properties received with this task message (may be None or {}). (versionadded 5.2) |
|
replaced_task_nesting: int - How many times the task was replaced, if at all (may be 0). (versionadded 5.2) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Celery Beat Sync Every Setting |
|
DESCRIPTION: The `beat_sync_every` setting determines the number of periodic tasks that can be called before another database sync is issued. It defaults to `0`. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/configuration.rst#_snippet_196 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
beat_sync_every: |
|
Default: 0 |
|
Description: The number of periodic tasks that can be called before another database sync is issued. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Configure GCS Result Backend Time-To-Live (TTL) |
|
DESCRIPTION: Sets the time-to-live for results stored in Google Cloud Storage, enabling automatic deletion after a specified duration. Requires a GCS bucket with 'Delete' Object Lifecycle Management action enabled. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/configuration.rst#_snippet_76 |
|
|
|
LANGUAGE: Python |
|
CODE: |
|
``` |
|
gcs_ttl = 86400 |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Skew countdown for tasks within a Celery group |
|
DESCRIPTION: Shows how to apply a `skew` to a group, setting a progressively increasing `countdown` for each task within the group. This can be used to stagger task execution over time. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/canvas.rst#_snippet_80 |
|
|
|
LANGUAGE: pycon |
|
CODE: |
|
``` |
|
>>> group.skew(start=1, stop=10)() |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Using the `~` prefix operator for task signatures |
|
DESCRIPTION: Demonstrates a shortcut for task signatures in the Python shell, equivalent to `sig.delay().get()`. This operator is generally not recommended for production code but is handy for experimentation. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/canvas.rst#_snippet_17 |
|
|
|
LANGUAGE: pycon |
|
CODE: |
|
``` |
|
>>> ~sig |
|
|
|
>>> # is the same as |
|
>>> sig.delay().get() |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Configure Celery Application Timezone |
|
DESCRIPTION: Sets the specific timezone for the Celery application. While all internal times and messages use UTC, this configuration ensures correct conversion to local time when workers process messages with time-sensitive parameters. |
|
|
|
SOURCE: https://github.com/celery/celery/blob/main/docs/getting-started/next-steps.rst#_snippet_57 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
app.conf.timezone = 'Europe/London' |
|
``` |