Tasks¶
Background task scheduling for running periodic operations.
Overview¶
The tasks module provides background task execution with interval-based and cron-based scheduling. Tasks run while the server is running and are automatically started after startup handlers and stopped before shutdown handlers.
Task Decorator¶
Register tasks using the @app.task() decorator on your Xitzin application:
from xitzin import Xitzin
app = Xitzin()
@app.task(interval="1h")
async def hourly_cleanup():
await cleanup_old_records()
@app.task(cron="0 2 * * *")
def daily_backup():
backup_database()
See the Application reference for the Xitzin.task() decorator API.
BackgroundTask¶
Data class representing a registered background task.
BackgroundTask
dataclass
¶
Configuration for a background task.
Helper Functions¶
parse_interval¶
parse_interval
¶
Parse interval string or int to seconds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interval
|
str | int | float
|
Either an integer/float (seconds) or string like "1h", "30m", "1d" |
required |
Returns:
| Type | Description |
|---|---|
float
|
Interval in seconds |
Raises:
| Type | Description |
|---|---|
ValueError
|
If format is invalid |
Source code in src/xitzin/tasks.py
run_interval_task¶
run_interval_task
async
¶
Run a task on a fixed interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task
|
BackgroundTask
|
The task to run |
required |
Source code in src/xitzin/tasks.py
run_cron_task¶
run_cron_task
async
¶
Run a task on a cron schedule.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task
|
BackgroundTask
|
The task to run |
required |
Source code in src/xitzin/tasks.py
Exceptions¶
TaskConfigurationError¶
TaskConfigurationError
¶
Bases: Exception
Raised when a background task is misconfigured.
This typically indicates mutually exclusive parameters were provided, or a required optional dependency is missing.
Example
@app.task() # Error: neither interval nor cron provided def my_task(): pass
@app.task(interval="1h", cron="* * * * *") # Error: both provided def my_task(): pass
Installation¶
Cron-based tasks require the croniter package:
Interval-based tasks work without any additional dependencies.