Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,17 +94,18 @@ Your experience with other drivers will be pretty similar. Just change the impor
# scheduler_example.py
import asyncio
from taskiq import TaskiqScheduler
from taskiq.schedule_sources import LabelScheduleSource
from taskiq_pg.asyncpg import AsyncpgBroker, AsyncpgScheduleSource


dsn = "postgres://taskiq_postgres:look_in_vault@localhost:5432/taskiq_postgres"
broker = AsyncpgBroker(dsn)
scheduler = TaskiqScheduler(
broker=broker,
sources=[AsyncpgScheduleSource(
dsn=dsn,
broker=broker,
)],
sources=[
LabelScheduleSource(broker),
AsyncpgScheduleSource(dsn=dsn),
],
)


Expand Down
36 changes: 20 additions & 16 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -200,17 +200,18 @@ Your experience with other drivers will be pretty similar. Just change the impor
# scheduler_example.py
import asyncio
from taskiq import TaskiqScheduler
from taskiq.schedule_sources import LabelScheduleSource
from taskiq_pg.asyncpg import AsyncpgBroker, AsyncpgScheduleSource


dsn = "postgres://taskiq_postgres:look_in_vault@localhost:5432/taskiq_postgres"
broker = AsyncpgBroker(dsn)
scheduler = TaskiqScheduler(
broker=broker,
sources=[AsyncpgScheduleSource(
dsn=dsn,
broker=broker,
)],
sources=[
LabelScheduleSource(broker),
AsyncpgScheduleSource(dsn=dsn),
],
)


Expand Down Expand Up @@ -239,17 +240,18 @@ Your experience with other drivers will be pretty similar. Just change the impor
# scheduler_example.py
import asyncio
from taskiq import TaskiqScheduler
from taskiq.schedule_sources import LabelScheduleSource
from taskiq_pg.psqlpy import PSQLPyBroker, PSQLPyScheduleSource


dsn = "postgres://taskiq_postgres:look_in_vault@localhost:5432/taskiq_postgres"
broker = PSQLPyBroker(dsn)
scheduler = TaskiqScheduler(
broker=broker,
sources=[PSQLPyScheduleSource(
dsn=dsn,
broker=broker,
)],
sources=[
LabelScheduleSource(broker),
PSQLPyScheduleSource(dsn=dsn),
],
)


Expand Down Expand Up @@ -279,17 +281,18 @@ Your experience with other drivers will be pretty similar. Just change the impor
# scheduler_example.py
import asyncio
from taskiq import TaskiqScheduler
from taskiq.schedule_sources import LabelScheduleSource
from taskiq_pg.psycopg import PsycopgBroker, PsycopgScheduleSource


dsn = "postgres://taskiq_postgres:look_in_vault@localhost:5432/taskiq_postgres"
broker = PsycopgBroker(dsn)
scheduler = TaskiqScheduler(
broker=broker,
sources=[PsycopgScheduleSource(
dsn=dsn,
broker=broker,
)],
sources=[
LabelScheduleSource(broker),
PsycopgScheduleSource(dsn=dsn),
],
)


Expand Down Expand Up @@ -319,17 +322,18 @@ Your experience with other drivers will be pretty similar. Just change the impor
# scheduler_example.py
import asyncio
from taskiq import TaskiqScheduler
from taskiq.schedule_sources import LabelScheduleSource
from taskiq_pg.aiopg import AiopgBroker, AiopgScheduleSource


dsn = "postgres://taskiq_postgres:look_in_vault@localhost:5432/taskiq_postgres"
broker = AiopgBroker(dsn)
scheduler = TaskiqScheduler(
broker=broker,
sources=[AiopgScheduleSource(
dsn=dsn,
broker=broker,
)],
sources=[
LabelScheduleSource(broker),
AiopgScheduleSource(dsn=dsn),
],
)


Expand Down
37 changes: 21 additions & 16 deletions docs/tutorial/schedule_source.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,27 @@ title: Schedule Source

## Basic usage

The easiest way to schedule task with this library is to add `schedule` label to task. Schedule source will automatically
parse this label and add new schedule to database on start of scheduler.
The PostgreSQL schedule source stores schedules in a database table: the schedules you add in runtime
(see below) and the ones you pre-populate the table with. They all survive application restarts.

You can define your scheduled task like this:
Schedules declared in task labels are not read by this source: they are handled by taskiq's built-in
`LabelScheduleSource`. Add both sources to your scheduler:

```python
import asyncio
from taskiq import TaskiqScheduler
from taskiq.schedule_sources import LabelScheduleSource
from taskiq_pg.asyncpg import AsyncpgBroker, AsyncpgScheduleSource


dsn = "postgres://taskiq_postgres:look_in_vault@localhost:5432/taskiq_postgres"
broker = AsyncpgBroker(dsn)
scheduler = TaskiqScheduler(
broker=broker,
sources=[AsyncpgScheduleSource(
dsn=dsn,
broker=broker,
)],
sources=[
LabelScheduleSource(broker), # schedules declared in task labels
AsyncpgScheduleSource(dsn=dsn), # schedules stored in PostgreSQL
],
)


Expand Down Expand Up @@ -59,10 +61,7 @@ You can also add schedules in runtime using `add_schedule` method of the schedul

dsn = "postgres://taskiq_postgres:look_in_vault@localhost:5432/taskiq_postgres"
broker = AsyncpgBroker(dsn)
schedule_source = AsyncpgScheduleSource(
dsn=dsn,
broker=broker,
)
schedule_source = AsyncpgScheduleSource(dsn=dsn)
scheduler = TaskiqScheduler(
broker=broker,
sources=[schedule_source],
Expand All @@ -82,24 +81,30 @@ You can also add schedules in runtime using `add_schedule` method of the schedul
await schedule_source.add_schedule(ScheduledTask(...))
```

Schedules stored in the database are never deleted on startup — they survive restarts.
One-shot (`time`) schedules are removed automatically after they fire.

## Using multiple schedules

You can use multiple schedules for one task. Just provide a list of schedules to the `@broker.task` decorator:
You can use multiple schedules for one task. Just provide a list of schedules to the `@broker.task` decorator.
These label-based schedules are picked up by `LabelScheduleSource`; the PostgreSQL source only stores
the schedules you add via `add_schedule`:

```python
import asyncio
from taskiq import TaskiqScheduler
from taskiq.schedule_sources import LabelScheduleSource
from taskiq_pg.asyncpg import AsyncpgBroker, AsyncpgScheduleSource


dsn = "postgres://taskiq_postgres:look_in_vault@localhost:5432/taskiq_postgres"
broker = AsyncpgBroker(dsn)
scheduler = TaskiqScheduler(
broker=broker,
sources=[AsyncpgScheduleSource(
dsn=dsn,
broker=broker,
)],
sources=[
LabelScheduleSource(broker),
AsyncpgScheduleSource(dsn=dsn),
],
)


Expand Down
2 changes: 1 addition & 1 deletion docs/tutorial/sharing_pool.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ async def main() -> None:
PsycopgResultBackend(pool=pool)
)

schedule_source = PsycopgScheduleSource(broker=broker, pool=pool)
schedule_source = PsycopgScheduleSource(pool=pool)
scheduler = TaskiqScheduler(broker=broker, sources=[schedule_source])

await broker.startup()
Expand Down
7 changes: 3 additions & 4 deletions examples/example_with_schedule_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import asyncio

from taskiq import TaskiqScheduler
from taskiq.schedule_sources import LabelScheduleSource

from taskiq_pg.psycopg import PsycopgBroker, PsycopgScheduleSource

Expand All @@ -20,10 +21,8 @@
scheduler = TaskiqScheduler(
broker=broker,
sources=[
PsycopgScheduleSource(
dsn=dsn,
broker=broker,
),
LabelScheduleSource(broker),
PsycopgScheduleSource(dsn=dsn),
],
)

Expand Down
60 changes: 3 additions & 57 deletions src/taskiq_pg/_internal/schedule_source.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,14 @@
import abc
import typing as tp
import uuid
from logging import getLogger

from pydantic import ValidationError
from taskiq import ScheduleSource
from taskiq.abc.broker import AsyncBroker
from taskiq.scheduler.scheduled_task import ScheduledTask

from taskiq_pg._internal.utils import DsnHelper


logger = getLogger("taskiq_pg")


class BasePostgresScheduleSource(ScheduleSource, DsnHelper, abc.ABC):
def __init__(
self,
broker: AsyncBroker,
dsn: str | tp.Callable[[], str] = "postgresql://postgres:postgres@localhost:5432/postgres",
table_name: str = "taskiq_schedules",
**connect_kwargs: tp.Any,
Expand All @@ -32,53 +23,8 @@ def __init__(
Args:
dsn: PostgreSQL connection string
table_name: Name of the table to store scheduled tasks. Will be created automatically if it doesn't exist.
broker: The TaskIQ broker instance to use for finding and managing tasks.
Required if startup_schedule is provided.
**connect_kwargs: Additional keyword arguments passed to the database connection pool.
"""
self._broker: tp.Final = broker
self._dsn: tp.Final = dsn
self._table_name: tp.Final = table_name
self._connect_kwargs: tp.Final = connect_kwargs

def extract_scheduled_tasks_from_broker(self) -> list[ScheduledTask]:
"""
Extract schedules from tasks that were registered in broker.

Returns:
A list of ScheduledTask instances extracted from the task's labels.
"""
scheduled_tasks_for_creation: list[ScheduledTask] = []
for task_name, task in self._broker.get_all_tasks().items():
if "schedule" not in task.labels:
logger.debug("Task %s has no schedule, skipping", task_name)
continue
if not isinstance(task.labels["schedule"], list):
logger.warning(
"Schedule for task %s is not a list, skipping",
task_name,
)
continue
for schedule in task.labels["schedule"]:
try:
new_schedule = ScheduledTask.model_validate(
{
"task_name": task_name,
"labels": schedule.get("labels", {}),
"args": schedule.get("args", []),
"kwargs": schedule.get("kwargs", {}),
"schedule_id": str(uuid.uuid4()),
"cron": schedule.get("cron", None),
"cron_offset": schedule.get("cron_offset", None),
"interval": schedule.get("interval", None),
"time": schedule.get("time", None),
},
)
scheduled_tasks_for_creation.append(new_schedule)
except ValidationError: # noqa: PERF203
logger.exception(
"Schedule for task %s is not valid, skipping",
task_name,
)
continue
return scheduled_tasks_for_creation
self._dsn: tp.Final[str | tp.Callable[[], str]] = dsn
self._table_name: tp.Final[str] = table_name
self._connect_kwargs: tp.Final[tp.Any] = connect_kwargs
4 changes: 0 additions & 4 deletions src/taskiq_pg/aiopg/queries.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,6 @@
FROM {};
"""

DELETE_ALL_SCHEDULES_QUERY = """
DELETE FROM {};
"""

DELETE_SCHEDULE_QUERY = """
DELETE FROM {} WHERE id = %s;
"""
Expand Down
Loading