grindsharp 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 REDX Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,204 @@
1
+ Metadata-Version: 2.4
2
+ Name: grindsharp
3
+ Version: 0.1.0
4
+ Summary: SQLite-first background jobs for Python. No Redis required.
5
+ Author: REDX Contributors
6
+ License: MIT
7
+ Keywords: background-jobs,queue,sqlite,worker,tasks,scheduler
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Topic :: Software Development :: Libraries
14
+ Classifier: Typing :: Typed
15
+ Requires-Python: >=3.9
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Provides-Extra: dev
19
+ Requires-Dist: pytest>=7.4; extra == "dev"
20
+ Dynamic: license-file
21
+
22
+ # Grindsharp
23
+
24
+ Most Python apps eventually need to do stuff in the background: send an email, process an upload, call a webhook, generate a report, retry something that flopped.
25
+
26
+ The usual setup works, but it can be overkill for a small app — Redis, a broker, worker containers, extra config, the whole mission.
27
+
28
+ Grindsharp is for the common case: you just want background jobs that are reliable and easy to run.
29
+
30
+ It uses **SQLite** by default. No Redis needed.
31
+
32
+ ## What you get
33
+
34
+ - A simple `@task` decorator
35
+ - `enqueue()`, `enqueue_in()`, `enqueue_at()`
36
+ - Retries with backoff
37
+ - A worker process (with basic concurrency)
38
+ - SQLite-backed job storage (WAL mode)
39
+ - Job status, crash recovery, and idempotent job IDs
40
+ - A small CLI for listing/retrying/stats
41
+
42
+ ## Install
43
+
44
+ ```bash
45
+ pip install -e .
46
+ ```
47
+
48
+ ## Quick start
49
+
50
+ ```python
51
+ # jobs.py
52
+ from grindsharp import Jobs
53
+
54
+ jobs = Jobs("jobs.db")
55
+
56
+ @jobs.task(retries=3, retry_backoff_seconds=30, timeout_seconds=60)
57
+ def send_receipt_email(user_id: int, invoice_id: str) -> None:
58
+ print(f"send receipt to user={user_id} invoice={invoice_id}")
59
+ ```
60
+
61
+ Enqueue work from your app:
62
+
63
+ ```python
64
+ from jobs import send_receipt_email
65
+
66
+ # run in the background
67
+ send_receipt_email.enqueue(user_id=42, invoice_id="inv_123")
68
+
69
+ # run later
70
+ send_receipt_email.enqueue_in(600, user_id=42, invoice_id="inv_123")
71
+
72
+ # avoid duplicates (idempotent job id)
73
+ send_receipt_email.enqueue(
74
+ user_id=42,
75
+ invoice_id="inv_123",
76
+ job_id="receipt:inv_123",
77
+ )
78
+
79
+ # if you want the existing job back instead of an error:
80
+ send_receipt_email.enqueue(
81
+ user_id=42,
82
+ invoice_id="inv_123",
83
+ job_id="receipt:inv_123",
84
+ if_exists="ignore",
85
+ )
86
+ ```
87
+
88
+ Run a worker:
89
+
90
+ ```bash
91
+ grindsharp worker --app jobs:jobs --db jobs.db
92
+ ```
93
+
94
+ That’s it: your web request returns quickly, and the worker handles the job.
95
+
96
+ ## FastAPI example
97
+
98
+ ```python
99
+ from fastapi import FastAPI
100
+ from grindsharp import Jobs
101
+
102
+ app = FastAPI()
103
+ jobs = Jobs("jobs.db")
104
+
105
+ @jobs.task(retries=3, retry_backoff_seconds=10)
106
+ def send_welcome_email(email: str) -> None:
107
+ ...
108
+
109
+ @app.post("/signup")
110
+ def signup(email: str):
111
+ send_welcome_email.enqueue(email=email)
112
+ return {"ok": True}
113
+ ```
114
+
115
+ Run the API and worker as separate processes:
116
+
117
+ ```bash
118
+ uvicorn app:app
119
+ grindsharp worker --app app:jobs --db jobs.db
120
+ ```
121
+
122
+ ## How jobs behave
123
+
124
+ - **Durable:** jobs are saved in SQLite, so they survive app restarts.
125
+ - **At-least-once:** if a worker crashes mid-job, that job might run again. So write tasks like they may be retried (because they might).
126
+ - **Retries:** failed jobs retry with backoff (`retry_backoff_seconds * attempt`).
127
+ - **Dead jobs:** when retries run out, the job gets marked `dead` and keeps the last error so you can see what happened.
128
+ - **Crash recovery:** stale `running` jobs get moved back to `pending` after a timeout.
129
+
130
+ ## CLI
131
+
132
+ ```bash
133
+ # run a worker
134
+ grindsharp worker --app jobs:jobs --db jobs.db --concurrency 4
135
+
136
+ # process one job then exit (useful for debugging)
137
+ grindsharp worker --app jobs:jobs --db jobs.db --once
138
+
139
+ # inspect jobs
140
+ grindsharp --db jobs.db list --status pending --limit 20
141
+ grindsharp --db jobs.db stats
142
+
143
+ # retry a dead/failed job
144
+ grindsharp --db jobs.db retry <job_id>
145
+
146
+ # clean up old succeeded jobs
147
+ grindsharp --db jobs.db purge --status succeeded --older-than-seconds 86400
148
+ ```
149
+
150
+ ## When Grindsharp is a good fit
151
+
152
+ Use it when you want background jobs without extra infrastructure:
153
+
154
+ - small/medium web apps
155
+ - internal tools and SaaS MVPs
156
+ - single-server deployments
157
+ - low-to-moderate job volume
158
+
159
+ ## When to use something else
160
+
161
+ - you need lots of workers spread across many machines
162
+ - you already run Redis/RabbitMQ and need the fancy queue features
163
+ - you need complex workflow/DAG orchestration
164
+
165
+ For many apps, a Postgres/Redis-backed queue is the next step up. Grindsharp is here to make the simple case easy.
166
+
167
+ ## Postgres / Redis backends
168
+
169
+ SQLite is the default. When you outgrow a single-node setup, Grindsharp can use a different store:
170
+
171
+ ```python
172
+ from grindsharp import Jobs, PostgresJobStore, RedisJobStore
173
+
174
+ # Postgres (pass a DBAPI connect callable, e.g. psycopg.connect)
175
+ jobs = Jobs(store=PostgresJobStore(connect=lambda: psycopg.connect(DB_URL)))
176
+
177
+ # Redis (pass a redis-py compatible client)
178
+ jobs = Jobs(store=RedisJobStore(redis.Redis.from_url(REDIS_URL)))
179
+ ```
180
+
181
+ These adapters keep the same `Jobs`/`Worker` API. Use SQLite for simple/local apps, Postgres for durable multi-worker SQL setups, and Redis for fast queue-style workloads.
182
+
183
+ ## Design notes
184
+
185
+ - Jobs are **at-least-once** (tasks should be idempotent).
186
+ - Payloads must be **JSON-serializable**.
187
+ - SQLite makes this a great fit for **small/medium single-node apps**. When you need distributed throughput, grow to a Postgres/Redis-style queue.
188
+
189
+ ## Development
190
+
191
+ ```bash
192
+ pip install -e .[dev]
193
+ pytest
194
+ ```
195
+
196
+ Integration tests (real services):
197
+
198
+ ```bash
199
+ docker compose -f docker-compose.integration.yml up -d
200
+ python -m pip install psycopg[binary] redis
201
+ python scripts/integration_test_backends.py
202
+ ```
203
+
204
+ This runs the same enqueue/retry/dead-job flow against real Postgres and Redis services.
@@ -0,0 +1,183 @@
1
+ # Grindsharp
2
+
3
+ Most Python apps eventually need to do stuff in the background: send an email, process an upload, call a webhook, generate a report, retry something that flopped.
4
+
5
+ The usual setup works, but it can be overkill for a small app — Redis, a broker, worker containers, extra config, the whole mission.
6
+
7
+ Grindsharp is for the common case: you just want background jobs that are reliable and easy to run.
8
+
9
+ It uses **SQLite** by default. No Redis needed.
10
+
11
+ ## What you get
12
+
13
+ - A simple `@task` decorator
14
+ - `enqueue()`, `enqueue_in()`, `enqueue_at()`
15
+ - Retries with backoff
16
+ - A worker process (with basic concurrency)
17
+ - SQLite-backed job storage (WAL mode)
18
+ - Job status, crash recovery, and idempotent job IDs
19
+ - A small CLI for listing/retrying/stats
20
+
21
+ ## Install
22
+
23
+ ```bash
24
+ pip install -e .
25
+ ```
26
+
27
+ ## Quick start
28
+
29
+ ```python
30
+ # jobs.py
31
+ from grindsharp import Jobs
32
+
33
+ jobs = Jobs("jobs.db")
34
+
35
+ @jobs.task(retries=3, retry_backoff_seconds=30, timeout_seconds=60)
36
+ def send_receipt_email(user_id: int, invoice_id: str) -> None:
37
+ print(f"send receipt to user={user_id} invoice={invoice_id}")
38
+ ```
39
+
40
+ Enqueue work from your app:
41
+
42
+ ```python
43
+ from jobs import send_receipt_email
44
+
45
+ # run in the background
46
+ send_receipt_email.enqueue(user_id=42, invoice_id="inv_123")
47
+
48
+ # run later
49
+ send_receipt_email.enqueue_in(600, user_id=42, invoice_id="inv_123")
50
+
51
+ # avoid duplicates (idempotent job id)
52
+ send_receipt_email.enqueue(
53
+ user_id=42,
54
+ invoice_id="inv_123",
55
+ job_id="receipt:inv_123",
56
+ )
57
+
58
+ # if you want the existing job back instead of an error:
59
+ send_receipt_email.enqueue(
60
+ user_id=42,
61
+ invoice_id="inv_123",
62
+ job_id="receipt:inv_123",
63
+ if_exists="ignore",
64
+ )
65
+ ```
66
+
67
+ Run a worker:
68
+
69
+ ```bash
70
+ grindsharp worker --app jobs:jobs --db jobs.db
71
+ ```
72
+
73
+ That’s it: your web request returns quickly, and the worker handles the job.
74
+
75
+ ## FastAPI example
76
+
77
+ ```python
78
+ from fastapi import FastAPI
79
+ from grindsharp import Jobs
80
+
81
+ app = FastAPI()
82
+ jobs = Jobs("jobs.db")
83
+
84
+ @jobs.task(retries=3, retry_backoff_seconds=10)
85
+ def send_welcome_email(email: str) -> None:
86
+ ...
87
+
88
+ @app.post("/signup")
89
+ def signup(email: str):
90
+ send_welcome_email.enqueue(email=email)
91
+ return {"ok": True}
92
+ ```
93
+
94
+ Run the API and worker as separate processes:
95
+
96
+ ```bash
97
+ uvicorn app:app
98
+ grindsharp worker --app app:jobs --db jobs.db
99
+ ```
100
+
101
+ ## How jobs behave
102
+
103
+ - **Durable:** jobs are saved in SQLite, so they survive app restarts.
104
+ - **At-least-once:** if a worker crashes mid-job, that job might run again. So write tasks like they may be retried (because they might).
105
+ - **Retries:** failed jobs retry with backoff (`retry_backoff_seconds * attempt`).
106
+ - **Dead jobs:** when retries run out, the job gets marked `dead` and keeps the last error so you can see what happened.
107
+ - **Crash recovery:** stale `running` jobs get moved back to `pending` after a timeout.
108
+
109
+ ## CLI
110
+
111
+ ```bash
112
+ # run a worker
113
+ grindsharp worker --app jobs:jobs --db jobs.db --concurrency 4
114
+
115
+ # process one job then exit (useful for debugging)
116
+ grindsharp worker --app jobs:jobs --db jobs.db --once
117
+
118
+ # inspect jobs
119
+ grindsharp --db jobs.db list --status pending --limit 20
120
+ grindsharp --db jobs.db stats
121
+
122
+ # retry a dead/failed job
123
+ grindsharp --db jobs.db retry <job_id>
124
+
125
+ # clean up old succeeded jobs
126
+ grindsharp --db jobs.db purge --status succeeded --older-than-seconds 86400
127
+ ```
128
+
129
+ ## When Grindsharp is a good fit
130
+
131
+ Use it when you want background jobs without extra infrastructure:
132
+
133
+ - small/medium web apps
134
+ - internal tools and SaaS MVPs
135
+ - single-server deployments
136
+ - low-to-moderate job volume
137
+
138
+ ## When to use something else
139
+
140
+ - you need lots of workers spread across many machines
141
+ - you already run Redis/RabbitMQ and need the fancy queue features
142
+ - you need complex workflow/DAG orchestration
143
+
144
+ For many apps, a Postgres/Redis-backed queue is the next step up. Grindsharp is here to make the simple case easy.
145
+
146
+ ## Postgres / Redis backends
147
+
148
+ SQLite is the default. When you outgrow a single-node setup, Grindsharp can use a different store:
149
+
150
+ ```python
151
+ from grindsharp import Jobs, PostgresJobStore, RedisJobStore
152
+
153
+ # Postgres (pass a DBAPI connect callable, e.g. psycopg.connect)
154
+ jobs = Jobs(store=PostgresJobStore(connect=lambda: psycopg.connect(DB_URL)))
155
+
156
+ # Redis (pass a redis-py compatible client)
157
+ jobs = Jobs(store=RedisJobStore(redis.Redis.from_url(REDIS_URL)))
158
+ ```
159
+
160
+ These adapters keep the same `Jobs`/`Worker` API. Use SQLite for simple/local apps, Postgres for durable multi-worker SQL setups, and Redis for fast queue-style workloads.
161
+
162
+ ## Design notes
163
+
164
+ - Jobs are **at-least-once** (tasks should be idempotent).
165
+ - Payloads must be **JSON-serializable**.
166
+ - SQLite makes this a great fit for **small/medium single-node apps**. When you need distributed throughput, grow to a Postgres/Redis-style queue.
167
+
168
+ ## Development
169
+
170
+ ```bash
171
+ pip install -e .[dev]
172
+ pytest
173
+ ```
174
+
175
+ Integration tests (real services):
176
+
177
+ ```bash
178
+ docker compose -f docker-compose.integration.yml up -d
179
+ python -m pip install psycopg[binary] redis
180
+ python scripts/integration_test_backends.py
181
+ ```
182
+
183
+ This runs the same enqueue/retry/dead-job flow against real Postgres and Redis services.
@@ -0,0 +1,45 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "grindsharp"
7
+ version = "0.1.0"
8
+ description = "SQLite-first background jobs for Python. No Redis required."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "REDX Contributors" }]
13
+ dependencies = []
14
+ keywords = ["background-jobs", "queue", "sqlite", "worker", "tasks", "scheduler"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Developers",
18
+ "License :: OSI Approved :: MIT License",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3 :: Only",
21
+ "Topic :: Software Development :: Libraries",
22
+ "Typing :: Typed",
23
+ ]
24
+
25
+ [project.optional-dependencies]
26
+ dev = ["pytest>=7.4"]
27
+
28
+ [project.scripts]
29
+ grindsharp = "grindsharp.cli:main"
30
+
31
+ [tool.setuptools]
32
+ package-dir = {"" = "src"}
33
+ include-package-data = true
34
+
35
+ [tool.setuptools.packages.find]
36
+ where = ["src"]
37
+ include = ["grindsharp*"]
38
+
39
+ [tool.setuptools.package-data]
40
+ grindsharp = ["py.typed"]
41
+
42
+ [tool.pytest.ini_options]
43
+ testpaths = ["tests"]
44
+ pythonpath = ["src"]
45
+ addopts = "-ra"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,23 @@
1
+ from .app import Jobs, Task
2
+ from .errors import DuplicateJob, InvalidTask, GrindsharpError, TaskNotFound
3
+ from .models import Job
4
+ from .store import SQLiteJobStore
5
+ from .postgres import PostgresJobStore
6
+ from .redis_store import RedisJobStore
7
+ from .worker import Worker
8
+
9
+ __all__ = [
10
+ "Jobs",
11
+ "Task",
12
+ "Worker",
13
+ "Job",
14
+ "SQLiteJobStore",
15
+ "PostgresJobStore",
16
+ "RedisJobStore",
17
+ "GrindsharpError",
18
+ "DuplicateJob",
19
+ "TaskNotFound",
20
+ "InvalidTask",
21
+ ]
22
+
23
+ __version__ = "0.1.0"
@@ -0,0 +1,4 @@
1
+ """Run grindsharp as a module: python -m grindsharp ..."""
2
+ from .cli import main
3
+
4
+ raise SystemExit(main())
@@ -0,0 +1,213 @@
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ import json
5
+ import uuid
6
+ from datetime import datetime, timedelta, timezone
7
+ from typing import Any, Callable, Generic, TypeVar
8
+
9
+ from .errors import DuplicateJob, InvalidTask, TaskNotFound
10
+ from .models import Job
11
+ from .store import SQLiteJobStore
12
+
13
+ F = TypeVar("F", bound=Callable[..., Any])
14
+
15
+
16
+ def _utcnow() -> datetime:
17
+ return datetime.now(timezone.utc)
18
+
19
+
20
+ def _default_job_id() -> str:
21
+ return "job_" + uuid.uuid4().hex
22
+
23
+
24
+ class Task(Generic[F]):
25
+ def __init__(
26
+ self,
27
+ func: F,
28
+ *,
29
+ jobs: "Jobs",
30
+ name: str,
31
+ retries: int = 0,
32
+ retry_backoff_seconds: int = 30,
33
+ timeout_seconds: int | None = None,
34
+ ):
35
+ self.func = func
36
+ self.jobs = jobs
37
+ self.name = name
38
+ self.retries = retries
39
+ self.retry_backoff_seconds = retry_backoff_seconds
40
+ self.timeout_seconds = timeout_seconds
41
+ self.__name__ = getattr(func, "__name__", name)
42
+ self.__doc__ = func.__doc__
43
+
44
+ def __call__(self, *args: Any, **kwargs: Any) -> Any:
45
+ return self.func(*args, **kwargs)
46
+
47
+ def enqueue(
48
+ self,
49
+ *args: Any,
50
+ job_id: str | None = None,
51
+ run_at: datetime | None = None,
52
+ priority: int = 0,
53
+ if_exists: str = "error",
54
+ **kwargs: Any,
55
+ ) -> Job:
56
+ payload = {"args": list(args), "kwargs": kwargs}
57
+ _ensure_jsonable(payload, self.name)
58
+ jid = job_id or _default_job_id()
59
+ return self.jobs.store.enqueue(
60
+ job_id=jid,
61
+ name=self.name,
62
+ payload=payload,
63
+ run_at=run_at,
64
+ max_retries=self.retries,
65
+ timeout_seconds=self.timeout_seconds,
66
+ priority=priority,
67
+ if_exists=if_exists,
68
+ )
69
+
70
+ def enqueue_in(self, seconds: float, *args: Any, **kwargs: Any) -> Job:
71
+ job_id = kwargs.pop("job_id", None)
72
+ priority = kwargs.pop("priority", 0)
73
+ if_exists = kwargs.pop("if_exists", "error")
74
+ run_at = _utcnow() + timedelta(seconds=seconds)
75
+ return self.enqueue(*args, job_id=job_id, run_at=run_at, priority=priority, if_exists=if_exists, **kwargs)
76
+
77
+ def enqueue_at(self, run_at: datetime, *args: Any, **kwargs: Any) -> Job:
78
+ job_id = kwargs.pop("job_id", None)
79
+ priority = kwargs.pop("priority", 0)
80
+ if_exists = kwargs.pop("if_exists", "error")
81
+ return self.enqueue(*args, job_id=job_id, run_at=run_at, priority=priority, if_exists=if_exists, **kwargs)
82
+
83
+ def delay(self, *args: Any, **kwargs: Any) -> Job:
84
+ """Alias for enqueue()."""
85
+ return self.enqueue(*args, **kwargs)
86
+
87
+
88
+ class PeriodicTask:
89
+ def __init__(self, task: Task[Any], *, every_seconds: float):
90
+ self.task = task
91
+ self.every_seconds = float(every_seconds)
92
+ self.name = task.name
93
+
94
+
95
+ class Jobs:
96
+ """Background job app.
97
+
98
+ Defaults to SQLite for zero-infrastructure local use. You can also pass a
99
+ custom store (e.g. PostgresJobStore / RedisJobStore) for larger deployments.
100
+ """
101
+
102
+ def __init__(self, db_path: str = "grindsharp.db", *, store: Any | None = None):
103
+ self.store = store or SQLiteJobStore(db_path)
104
+ self.tasks: dict[str, Task[Any]] = {}
105
+ self.periodic: list[PeriodicTask] = []
106
+
107
+ def close(self) -> None:
108
+ self.store.close()
109
+
110
+ def task(
111
+ self,
112
+ func: F | None = None,
113
+ *,
114
+ name: str | None = None,
115
+ retries: int = 0,
116
+ retry_backoff_seconds: int = 30,
117
+ timeout_seconds: int | None = None,
118
+ ) -> Any:
119
+ def decorator(fn: F) -> Task[F]:
120
+ task_name = name or _task_name(fn)
121
+ if not task_name:
122
+ raise InvalidTask("Task function must have a resolvable name")
123
+ task = Task(
124
+ fn,
125
+ jobs=self,
126
+ name=task_name,
127
+ retries=retries,
128
+ retry_backoff_seconds=retry_backoff_seconds,
129
+ timeout_seconds=timeout_seconds,
130
+ )
131
+ self.tasks[task_name] = task
132
+ return task
133
+
134
+ if func is not None:
135
+ return decorator(func)
136
+ return decorator
137
+
138
+ def register(self, task: Task[Any]) -> Task[Any]:
139
+ self.tasks[task.name] = task
140
+ return task
141
+
142
+ def get_task(self, name: str) -> Task[Any]:
143
+ task = self.tasks.get(name)
144
+ if not task:
145
+ raise TaskNotFound(f"No task registered as '{name}'")
146
+ return task
147
+
148
+ def every(self, seconds: float, *, name: str | None = None, retries: int = 0, retry_backoff_seconds: int = 30, timeout_seconds: int | None = None) -> Any:
149
+ """Decorator to register a periodic task (no args).
150
+
151
+ Use jobs.tick() or run the worker (it ticks automatically) to enqueue due runs.
152
+ """
153
+ def decorator(fn: F) -> Task[F]:
154
+ task = self.task(fn, name=name, retries=retries, retry_backoff_seconds=retry_backoff_seconds, timeout_seconds=timeout_seconds)
155
+ self.periodic.append(PeriodicTask(task, every_seconds=seconds))
156
+ return task
157
+ return decorator
158
+
159
+ def tick(self, *, now: datetime | None = None) -> list[Job]:
160
+ """Enqueue due periodic tasks. Safe to call often (idempotent per time slot)."""
161
+ now = now or _utcnow()
162
+ enqueued: list[Job] = []
163
+ for sched in self.periodic:
164
+ slot = int(now.timestamp() // sched.every_seconds)
165
+ job_id = f"periodic:{sched.name}:{slot}"
166
+ run_at = datetime.fromtimestamp(slot * sched.every_seconds, tz=timezone.utc)
167
+ try:
168
+ job = sched.task.enqueue(job_id=job_id, run_at=run_at, if_exists="ignore")
169
+ # only count if this tick created/found the slot job and it's pending/recent
170
+ if job.id == job_id:
171
+ enqueued.append(job)
172
+ except Exception:
173
+ # don't let one bad schedule break others
174
+ continue
175
+ return enqueued
176
+
177
+ def enqueue(self, name: str, *args: Any, **kwargs: Any) -> Job:
178
+ task = self.get_task(name)
179
+ return task.enqueue(*args, **kwargs)
180
+
181
+ def run_job(self, job: Job) -> Any:
182
+ task = self.get_task(job.name)
183
+ args = job.payload.get("args", [])
184
+ kwargs = job.payload.get("kwargs", {})
185
+ return task(*args, **kwargs)
186
+
187
+ def get_job(self, job_id: str) -> Job | None:
188
+ return self.store.get(job_id)
189
+
190
+ def list_jobs(self, **kwargs: Any) -> list[Job]:
191
+ return self.store.list_jobs(**kwargs)
192
+
193
+ def cancel_job(self, job_id: str) -> Job | None:
194
+ return self.store.cancel(job_id)
195
+
196
+ def retry_job(self, job_id: str) -> Job | None:
197
+ return self.store.retry_job(job_id)
198
+
199
+
200
+ def _task_name(func: Callable[..., Any]) -> str:
201
+ module = getattr(func, "__module__", "") or ""
202
+ qualname = getattr(func, "__qualname__", getattr(func, "__name__", ""))
203
+ # avoid non-importable names like <locals>
204
+ if "<locals>" in qualname:
205
+ return qualname
206
+ return f"{module}:{qualname}" if module else qualname
207
+
208
+
209
+ def _ensure_jsonable(value: Any, task_name: str) -> None:
210
+ try:
211
+ json.dumps(value)
212
+ except TypeError as e:
213
+ raise InvalidTask(f"Task '{task_name}' arguments must be JSON-serializable") from e