ErisPulse-Cron 1.0.0__py3-none-any.whl
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.
- Cron/Core.py +197 -0
- Cron/__init__.py +1 -0
- Cron/scheduler.py +261 -0
- Cron/store.py +225 -0
- erispulse_cron-1.0.0.dist-info/METADATA +9 -0
- erispulse_cron-1.0.0.dist-info/RECORD +9 -0
- erispulse_cron-1.0.0.dist-info/WHEEL +5 -0
- erispulse_cron-1.0.0.dist-info/entry_points.txt +2 -0
- erispulse_cron-1.0.0.dist-info/top_level.txt +1 -0
Cron/Core.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import time
|
|
2
|
+
from typing import Any, Awaitable, Callable, Dict, List, Optional
|
|
3
|
+
|
|
4
|
+
from ErisPulse import sdk
|
|
5
|
+
from ErisPulse.Core.Bases import BaseModule
|
|
6
|
+
from ErisPulse.loaders import ModuleLoadStrategy
|
|
7
|
+
|
|
8
|
+
from .scheduler import Scheduler, TriggerHandler
|
|
9
|
+
from .store import Store
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Main(BaseModule):
|
|
13
|
+
def __init__(self):
|
|
14
|
+
self.sdk = sdk
|
|
15
|
+
self.logger = sdk.logger.get_child("Cron")
|
|
16
|
+
self._store: Optional[Store] = None
|
|
17
|
+
self._scheduler: Optional[Scheduler] = None
|
|
18
|
+
|
|
19
|
+
@staticmethod
|
|
20
|
+
def get_load_strategy():
|
|
21
|
+
return ModuleLoadStrategy(
|
|
22
|
+
lazy_load=False,
|
|
23
|
+
priority=100,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
def _ensure_initialized(self):
|
|
27
|
+
if self._store is None or self._scheduler is None:
|
|
28
|
+
raise RuntimeError("Cron module is not loaded yet")
|
|
29
|
+
|
|
30
|
+
async def on_load(self, event):
|
|
31
|
+
self._store = Store()
|
|
32
|
+
self._scheduler = Scheduler(self._store)
|
|
33
|
+
await self._scheduler.start()
|
|
34
|
+
self.logger.info("Cron module loaded")
|
|
35
|
+
|
|
36
|
+
async def on_unload(self, event):
|
|
37
|
+
if self._scheduler:
|
|
38
|
+
await self._scheduler.stop()
|
|
39
|
+
self.logger.info("Cron module unloaded")
|
|
40
|
+
|
|
41
|
+
# ==================== Public API ====================
|
|
42
|
+
|
|
43
|
+
def once(self,
|
|
44
|
+
delay: Optional[float] = None,
|
|
45
|
+
trigger_at: Optional[float] = None,
|
|
46
|
+
callback_data: Any = None,
|
|
47
|
+
label: Optional[str] = None,
|
|
48
|
+
source: Optional[str] = None,
|
|
49
|
+
missed_policy: str = "fire_immediately") -> str:
|
|
50
|
+
self._ensure_initialized()
|
|
51
|
+
|
|
52
|
+
if delay is not None and trigger_at is not None:
|
|
53
|
+
raise ValueError("Specify either 'delay' or 'trigger_at', not both")
|
|
54
|
+
if delay is None and trigger_at is None:
|
|
55
|
+
raise ValueError("Must specify either 'delay' or 'trigger_at'")
|
|
56
|
+
|
|
57
|
+
next_run = self._scheduler.calc_first_next_run(
|
|
58
|
+
"once", trigger_at=trigger_at, delay=delay
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
actual_trigger_at = trigger_at if trigger_at is not None else (time.time() + delay)
|
|
62
|
+
|
|
63
|
+
return self._store.create_task(
|
|
64
|
+
task_type="once",
|
|
65
|
+
trigger_at=actual_trigger_at,
|
|
66
|
+
callback_data=callback_data,
|
|
67
|
+
label=label,
|
|
68
|
+
source=source,
|
|
69
|
+
next_run=next_run,
|
|
70
|
+
missed_policy=missed_policy,
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
def interval(self,
|
|
74
|
+
interval_seconds: float,
|
|
75
|
+
callback_data: Any = None,
|
|
76
|
+
delay: Optional[float] = None,
|
|
77
|
+
max_runs: int = 0,
|
|
78
|
+
label: Optional[str] = None,
|
|
79
|
+
source: Optional[str] = None,
|
|
80
|
+
missed_policy: str = "fire_immediately") -> str:
|
|
81
|
+
self._ensure_initialized()
|
|
82
|
+
|
|
83
|
+
if interval_seconds <= 0:
|
|
84
|
+
raise ValueError("interval_seconds must be > 0")
|
|
85
|
+
|
|
86
|
+
next_run = self._scheduler.calc_first_next_run(
|
|
87
|
+
"interval",
|
|
88
|
+
interval_seconds=interval_seconds,
|
|
89
|
+
delay=delay,
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
return self._store.create_task(
|
|
93
|
+
task_type="interval",
|
|
94
|
+
interval_seconds=interval_seconds,
|
|
95
|
+
callback_data=callback_data,
|
|
96
|
+
label=label,
|
|
97
|
+
source=source,
|
|
98
|
+
next_run=next_run,
|
|
99
|
+
max_runs=max_runs,
|
|
100
|
+
missed_policy=missed_policy,
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
def cron(self,
|
|
104
|
+
expression: str,
|
|
105
|
+
callback_data: Any = None,
|
|
106
|
+
timezone: str = "Asia/Shanghai",
|
|
107
|
+
max_runs: int = 0,
|
|
108
|
+
label: Optional[str] = None,
|
|
109
|
+
source: Optional[str] = None,
|
|
110
|
+
missed_policy: str = "fire_immediately") -> str:
|
|
111
|
+
self._ensure_initialized()
|
|
112
|
+
|
|
113
|
+
next_run = self._scheduler.calc_first_next_run(
|
|
114
|
+
"cron",
|
|
115
|
+
cron_expr=expression,
|
|
116
|
+
cron_timezone=timezone,
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
return self._store.create_task(
|
|
120
|
+
task_type="cron",
|
|
121
|
+
cron_expr=expression,
|
|
122
|
+
cron_timezone=timezone,
|
|
123
|
+
callback_data=callback_data,
|
|
124
|
+
label=label,
|
|
125
|
+
source=source,
|
|
126
|
+
next_run=next_run,
|
|
127
|
+
max_runs=max_runs,
|
|
128
|
+
missed_policy=missed_policy,
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
def on_trigger(self, handler: TriggerHandler) -> TriggerHandler:
|
|
132
|
+
self._ensure_initialized()
|
|
133
|
+
self._scheduler.register_handler(handler)
|
|
134
|
+
return handler
|
|
135
|
+
|
|
136
|
+
def off_trigger(self, handler: TriggerHandler):
|
|
137
|
+
self._ensure_initialized()
|
|
138
|
+
self._scheduler.unregister_handler(handler)
|
|
139
|
+
|
|
140
|
+
def cancel(self, task_id: str) -> bool:
|
|
141
|
+
self._ensure_initialized()
|
|
142
|
+
task = self._store.get_task(task_id)
|
|
143
|
+
if task is None:
|
|
144
|
+
return False
|
|
145
|
+
if task.get("status") not in ("pending", "paused"):
|
|
146
|
+
return False
|
|
147
|
+
return self._store.cancel_task(task_id)
|
|
148
|
+
|
|
149
|
+
def pause(self, task_id: str) -> bool:
|
|
150
|
+
self._ensure_initialized()
|
|
151
|
+
task = self._store.get_task(task_id)
|
|
152
|
+
if task is None:
|
|
153
|
+
return False
|
|
154
|
+
if task.get("status") != "pending":
|
|
155
|
+
return False
|
|
156
|
+
return self._store.pause_task(task_id)
|
|
157
|
+
|
|
158
|
+
def resume(self, task_id: str, *, reschedule: bool = False) -> bool:
|
|
159
|
+
self._ensure_initialized()
|
|
160
|
+
task = self._store.get_task(task_id)
|
|
161
|
+
if task is None:
|
|
162
|
+
return False
|
|
163
|
+
if task.get("status") != "paused":
|
|
164
|
+
return False
|
|
165
|
+
|
|
166
|
+
if reschedule:
|
|
167
|
+
now = time.time()
|
|
168
|
+
next_run = self._scheduler._calc_next_run(task, now)
|
|
169
|
+
if next_run is None:
|
|
170
|
+
next_run = now
|
|
171
|
+
else:
|
|
172
|
+
next_run = task.get("next_run", time.time())
|
|
173
|
+
|
|
174
|
+
return self._store.resume_task(task_id, next_run)
|
|
175
|
+
|
|
176
|
+
def get_task(self, task_id: str) -> Optional[dict]:
|
|
177
|
+
self._ensure_initialized()
|
|
178
|
+
return self._store.get_task(task_id)
|
|
179
|
+
|
|
180
|
+
def list_tasks(self,
|
|
181
|
+
source: Optional[str] = None,
|
|
182
|
+
status: Optional[str] = None,
|
|
183
|
+
task_type: Optional[str] = None) -> List[dict]:
|
|
184
|
+
self._ensure_initialized()
|
|
185
|
+
return self._store.list_tasks(source=source, status=status, task_type=task_type)
|
|
186
|
+
|
|
187
|
+
async def trigger_now(self, task_id: str) -> Optional[dict]:
|
|
188
|
+
self._ensure_initialized()
|
|
189
|
+
return await self._scheduler.trigger_task_now(task_id)
|
|
190
|
+
|
|
191
|
+
def delete_task(self, task_id: str) -> bool:
|
|
192
|
+
self._ensure_initialized()
|
|
193
|
+
return self._store.delete_task(task_id)
|
|
194
|
+
|
|
195
|
+
def cleanup(self, max_age_seconds: float = 86400 * 7) -> int:
|
|
196
|
+
self._ensure_initialized()
|
|
197
|
+
return self._store.cleanup_completed(max_age_seconds)
|
Cron/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .Core import Main
|
Cron/scheduler.py
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import time
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
from typing import Any, Awaitable, Callable, Dict, List, Optional
|
|
5
|
+
|
|
6
|
+
try:
|
|
7
|
+
from zoneinfo import ZoneInfo
|
|
8
|
+
_HAS_ZONEINFO = True
|
|
9
|
+
try:
|
|
10
|
+
ZoneInfo("Asia/Shanghai")
|
|
11
|
+
except Exception:
|
|
12
|
+
_HAS_ZONEINFO = False
|
|
13
|
+
except ImportError:
|
|
14
|
+
_HAS_ZONEINFO = False
|
|
15
|
+
|
|
16
|
+
from croniter import croniter
|
|
17
|
+
|
|
18
|
+
from ErisPulse import sdk
|
|
19
|
+
|
|
20
|
+
from .store import Store
|
|
21
|
+
|
|
22
|
+
POLL_INTERVAL = 1.0
|
|
23
|
+
|
|
24
|
+
TriggerHandler = Callable[[Dict[str, Any]], Awaitable[None]]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _make_cron_dt(timestamp: float, tz_name: str) -> datetime:
|
|
28
|
+
if _HAS_ZONEINFO:
|
|
29
|
+
try:
|
|
30
|
+
tz = ZoneInfo(tz_name)
|
|
31
|
+
return datetime.fromtimestamp(timestamp, tz=tz)
|
|
32
|
+
except Exception:
|
|
33
|
+
pass
|
|
34
|
+
return datetime.fromtimestamp(timestamp)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class Scheduler:
|
|
38
|
+
def __init__(self, store: Store):
|
|
39
|
+
self.store = store
|
|
40
|
+
self.logger = sdk.logger.get_child("Cron").scheduler
|
|
41
|
+
self._running = False
|
|
42
|
+
self._task: Optional[asyncio.Task] = None
|
|
43
|
+
self._handlers: List[TriggerHandler] = []
|
|
44
|
+
if not _HAS_ZONEINFO:
|
|
45
|
+
self.logger.warning("zoneinfo 不可用,Cron 任务将使用系统本地时间")
|
|
46
|
+
|
|
47
|
+
@property
|
|
48
|
+
def is_running(self) -> bool:
|
|
49
|
+
return self._running
|
|
50
|
+
|
|
51
|
+
def register_handler(self, handler: TriggerHandler):
|
|
52
|
+
if handler not in self._handlers:
|
|
53
|
+
self._handlers.append(handler)
|
|
54
|
+
self.logger.debug(f"Registered trigger handler: {getattr(handler, '__name__', repr(handler))}")
|
|
55
|
+
|
|
56
|
+
def unregister_handler(self, handler: TriggerHandler):
|
|
57
|
+
self._handlers = [h for h in self._handlers if h is not handler]
|
|
58
|
+
|
|
59
|
+
async def start(self):
|
|
60
|
+
if self._running:
|
|
61
|
+
return
|
|
62
|
+
self._running = True
|
|
63
|
+
self._recover_tasks()
|
|
64
|
+
self._task = asyncio.create_task(self._poll_loop())
|
|
65
|
+
self.logger.info("Scheduler started")
|
|
66
|
+
|
|
67
|
+
async def stop(self):
|
|
68
|
+
self._running = False
|
|
69
|
+
if self._task and not self._task.done():
|
|
70
|
+
self._task.cancel()
|
|
71
|
+
try:
|
|
72
|
+
await self._task
|
|
73
|
+
except asyncio.CancelledError:
|
|
74
|
+
pass
|
|
75
|
+
self._task = None
|
|
76
|
+
self.logger.info("Scheduler stopped")
|
|
77
|
+
|
|
78
|
+
def _recover_tasks(self):
|
|
79
|
+
tasks = self.store.get_all_active_tasks()
|
|
80
|
+
now = time.time()
|
|
81
|
+
recovered = 0
|
|
82
|
+
|
|
83
|
+
for task in tasks:
|
|
84
|
+
task_type = task.get("type")
|
|
85
|
+
next_run = task.get("next_run", 0)
|
|
86
|
+
|
|
87
|
+
if next_run <= now:
|
|
88
|
+
policy = task.get("missed_policy", "fire_immediately")
|
|
89
|
+
|
|
90
|
+
if policy == "skip":
|
|
91
|
+
new_next = self._calc_next_run(task, now)
|
|
92
|
+
if new_next is not None:
|
|
93
|
+
self.store.update_task(task["id"], next_run=new_next)
|
|
94
|
+
else:
|
|
95
|
+
self.store.mark_completed(task["id"])
|
|
96
|
+
continue
|
|
97
|
+
elif policy == "reschedule":
|
|
98
|
+
new_next = self._calc_next_run(task, now)
|
|
99
|
+
if new_next is not None:
|
|
100
|
+
self.store.update_task(task["id"], next_run=new_next)
|
|
101
|
+
else:
|
|
102
|
+
self.store.mark_completed(task["id"])
|
|
103
|
+
continue
|
|
104
|
+
else:
|
|
105
|
+
self.store.update_task(task["id"], next_run=now)
|
|
106
|
+
|
|
107
|
+
recovered += 1
|
|
108
|
+
|
|
109
|
+
self.logger.info(f"Recovered {recovered} active tasks ({len(tasks)} total loaded)")
|
|
110
|
+
|
|
111
|
+
def _calc_next_run(self, task: dict, base_time: Optional[float] = None) -> Optional[float]:
|
|
112
|
+
base_time = base_time or time.time()
|
|
113
|
+
task_type = task.get("type")
|
|
114
|
+
|
|
115
|
+
if task_type == "once":
|
|
116
|
+
return None
|
|
117
|
+
|
|
118
|
+
if task_type == "interval":
|
|
119
|
+
interval = task.get("interval_seconds", 0)
|
|
120
|
+
if interval <= 0:
|
|
121
|
+
return None
|
|
122
|
+
return base_time + interval
|
|
123
|
+
|
|
124
|
+
if task_type == "cron":
|
|
125
|
+
cron_expr = task.get("cron_expr")
|
|
126
|
+
if not cron_expr:
|
|
127
|
+
return None
|
|
128
|
+
tz_name = task.get("cron_timezone", "Asia/Shanghai")
|
|
129
|
+
try:
|
|
130
|
+
dt = _make_cron_dt(base_time, tz_name)
|
|
131
|
+
cron = croniter(cron_expr, dt)
|
|
132
|
+
next_dt = cron.get_next(datetime)
|
|
133
|
+
return next_dt.timestamp()
|
|
134
|
+
except Exception as e:
|
|
135
|
+
self.logger.error(f"Failed to calc next run for cron '{cron_expr}': {e}")
|
|
136
|
+
return None
|
|
137
|
+
|
|
138
|
+
return None
|
|
139
|
+
|
|
140
|
+
def calc_first_next_run(self, task_type: str, *, trigger_at: Optional[float] = None,
|
|
141
|
+
interval_seconds: Optional[float] = None,
|
|
142
|
+
cron_expr: Optional[str] = None,
|
|
143
|
+
cron_timezone: str = "Asia/Shanghai",
|
|
144
|
+
delay: Optional[float] = None) -> float:
|
|
145
|
+
now = time.time()
|
|
146
|
+
|
|
147
|
+
if task_type == "once":
|
|
148
|
+
if delay is not None and delay > 0:
|
|
149
|
+
return now + delay
|
|
150
|
+
if trigger_at is not None:
|
|
151
|
+
return trigger_at
|
|
152
|
+
return now
|
|
153
|
+
|
|
154
|
+
if task_type == "interval":
|
|
155
|
+
interval = interval_seconds or 0
|
|
156
|
+
if interval <= 0:
|
|
157
|
+
raise ValueError("interval_seconds must be > 0")
|
|
158
|
+
if delay is not None and delay > 0:
|
|
159
|
+
return now + delay
|
|
160
|
+
return now + interval
|
|
161
|
+
|
|
162
|
+
if task_type == "cron":
|
|
163
|
+
if not cron_expr:
|
|
164
|
+
raise ValueError("cron_expr is required for cron tasks")
|
|
165
|
+
dt = _make_cron_dt(now, cron_timezone)
|
|
166
|
+
cron = croniter(cron_expr, dt)
|
|
167
|
+
next_dt = cron.get_next(datetime)
|
|
168
|
+
return next_dt.timestamp()
|
|
169
|
+
|
|
170
|
+
raise ValueError(f"Unknown task type: {task_type}")
|
|
171
|
+
|
|
172
|
+
async def _poll_loop(self):
|
|
173
|
+
try:
|
|
174
|
+
while self._running:
|
|
175
|
+
try:
|
|
176
|
+
await self._tick()
|
|
177
|
+
except asyncio.CancelledError:
|
|
178
|
+
raise
|
|
179
|
+
except Exception as e:
|
|
180
|
+
self.logger.error(f"Tick error: {e}")
|
|
181
|
+
await asyncio.sleep(POLL_INTERVAL)
|
|
182
|
+
except asyncio.CancelledError:
|
|
183
|
+
pass
|
|
184
|
+
|
|
185
|
+
async def _tick(self):
|
|
186
|
+
pending = self.store.get_pending_tasks()
|
|
187
|
+
if not pending:
|
|
188
|
+
return
|
|
189
|
+
|
|
190
|
+
now = time.time()
|
|
191
|
+
for task in pending:
|
|
192
|
+
if task.get("next_run", now + 1) > now:
|
|
193
|
+
continue
|
|
194
|
+
|
|
195
|
+
task_type = task.get("type")
|
|
196
|
+
task_id = task.get("id")
|
|
197
|
+
trigger_time = time.time()
|
|
198
|
+
|
|
199
|
+
trigger_info = self._build_trigger_info(task, trigger_time)
|
|
200
|
+
|
|
201
|
+
await self._fire_handlers(trigger_info)
|
|
202
|
+
|
|
203
|
+
if task_type == "once":
|
|
204
|
+
self.store.mark_completed(task_id)
|
|
205
|
+
elif task_type == "interval":
|
|
206
|
+
interval = task.get("interval_seconds", 0)
|
|
207
|
+
next_run = trigger_time + interval
|
|
208
|
+
self.store.increment_run(task_id, next_run=next_run)
|
|
209
|
+
elif task_type == "cron":
|
|
210
|
+
next_run = self._calc_next_run(task, trigger_time)
|
|
211
|
+
if next_run is not None:
|
|
212
|
+
self.store.increment_run(task_id, next_run=next_run)
|
|
213
|
+
else:
|
|
214
|
+
self.store.mark_completed(task_id)
|
|
215
|
+
|
|
216
|
+
def _build_trigger_info(self, task: dict, trigger_time: float) -> dict:
|
|
217
|
+
return {
|
|
218
|
+
"task_id": task.get("id"),
|
|
219
|
+
"task_type": task.get("type"),
|
|
220
|
+
"callback_data": task.get("callback_data"),
|
|
221
|
+
"label": task.get("label"),
|
|
222
|
+
"source": task.get("source"),
|
|
223
|
+
"run_count": task.get("run_count", 0) + 1,
|
|
224
|
+
"max_runs": task.get("max_runs", 0),
|
|
225
|
+
"created_at": task.get("created_at"),
|
|
226
|
+
"last_run": task.get("last_run"),
|
|
227
|
+
"trigger_time": trigger_time,
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
async def _fire_handlers(self, trigger_info: dict):
|
|
231
|
+
for handler in self._handlers:
|
|
232
|
+
try:
|
|
233
|
+
await handler(trigger_info)
|
|
234
|
+
except asyncio.CancelledError:
|
|
235
|
+
raise
|
|
236
|
+
except Exception as e:
|
|
237
|
+
handler_name = getattr(handler, "__name__", repr(handler))
|
|
238
|
+
self.logger.error(f"Handler '{handler_name}' error for task "
|
|
239
|
+
f"{trigger_info.get('task_id')}: {e}")
|
|
240
|
+
|
|
241
|
+
async def trigger_task_now(self, task_id: str) -> Optional[dict]:
|
|
242
|
+
task = self.store.get_task(task_id)
|
|
243
|
+
if task is None:
|
|
244
|
+
return None
|
|
245
|
+
if task.get("status") not in ("pending", "paused"):
|
|
246
|
+
return None
|
|
247
|
+
|
|
248
|
+
trigger_info = self._build_trigger_info(task, time.time())
|
|
249
|
+
await self._fire_handlers(trigger_info)
|
|
250
|
+
|
|
251
|
+
task_type = task.get("type")
|
|
252
|
+
if task_type == "once":
|
|
253
|
+
self.store.mark_completed(task_id)
|
|
254
|
+
else:
|
|
255
|
+
next_run = self._calc_next_run(task)
|
|
256
|
+
if next_run is not None:
|
|
257
|
+
self.store.increment_run(task_id, next_run=next_run)
|
|
258
|
+
else:
|
|
259
|
+
self.store.mark_completed(task_id)
|
|
260
|
+
|
|
261
|
+
return trigger_info
|
Cron/store.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import time
|
|
3
|
+
import uuid
|
|
4
|
+
from typing import Any, Dict, List, Optional
|
|
5
|
+
|
|
6
|
+
from ErisPulse import sdk
|
|
7
|
+
|
|
8
|
+
TABLE_NAME = "cron_tasks"
|
|
9
|
+
|
|
10
|
+
COLUMNS = {
|
|
11
|
+
"id": "TEXT PRIMARY KEY",
|
|
12
|
+
"type": "TEXT NOT NULL",
|
|
13
|
+
"status": "TEXT NOT NULL DEFAULT 'pending'",
|
|
14
|
+
"trigger_at": "REAL",
|
|
15
|
+
"interval_seconds": "REAL",
|
|
16
|
+
"cron_expr": "TEXT",
|
|
17
|
+
"cron_timezone": "TEXT DEFAULT 'Asia/Shanghai'",
|
|
18
|
+
"callback_data": "TEXT",
|
|
19
|
+
"label": "TEXT",
|
|
20
|
+
"source": "TEXT",
|
|
21
|
+
"created_at": "REAL NOT NULL",
|
|
22
|
+
"last_run": "REAL",
|
|
23
|
+
"next_run": "REAL NOT NULL",
|
|
24
|
+
"run_count": "INTEGER DEFAULT 0",
|
|
25
|
+
"max_runs": "INTEGER DEFAULT 0",
|
|
26
|
+
"missed_policy": "TEXT DEFAULT 'fire_immediately'",
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
COLUMN_NAMES = list(COLUMNS.keys())
|
|
30
|
+
|
|
31
|
+
VALID_TYPES = {"once", "interval", "cron"}
|
|
32
|
+
VALID_STATUSES = {"pending", "paused", "completed", "cancelled"}
|
|
33
|
+
VALID_MISSED_POLICIES = {"fire_immediately", "skip", "reschedule"}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Store:
|
|
37
|
+
def __init__(self):
|
|
38
|
+
self._ensure_table()
|
|
39
|
+
|
|
40
|
+
def _ensure_table(self):
|
|
41
|
+
sdk.storage.CreateTable(TABLE_NAME, COLUMNS)
|
|
42
|
+
|
|
43
|
+
@staticmethod
|
|
44
|
+
def _row_to_dict(row) -> Optional[dict]:
|
|
45
|
+
if row is None:
|
|
46
|
+
return None
|
|
47
|
+
if isinstance(row, dict):
|
|
48
|
+
result = dict(row)
|
|
49
|
+
elif isinstance(row, (tuple, list)):
|
|
50
|
+
result = dict(zip(COLUMN_NAMES, row))
|
|
51
|
+
else:
|
|
52
|
+
return None
|
|
53
|
+
if "callback_data" in result and isinstance(result["callback_data"], str):
|
|
54
|
+
try:
|
|
55
|
+
result["callback_data"] = json.loads(result["callback_data"])
|
|
56
|
+
except (json.JSONDecodeError, TypeError):
|
|
57
|
+
pass
|
|
58
|
+
return result
|
|
59
|
+
|
|
60
|
+
@staticmethod
|
|
61
|
+
def _rows_to_dicts(rows) -> List[dict]:
|
|
62
|
+
return [Store._row_to_dict(r) for r in rows]
|
|
63
|
+
|
|
64
|
+
@staticmethod
|
|
65
|
+
def _rows_to_single(rows, col_index: int = 0) -> list:
|
|
66
|
+
results = []
|
|
67
|
+
for row in rows:
|
|
68
|
+
if isinstance(row, (tuple, list)):
|
|
69
|
+
results.append(row[col_index])
|
|
70
|
+
elif isinstance(row, dict):
|
|
71
|
+
results.append(list(row.values())[col_index])
|
|
72
|
+
return results
|
|
73
|
+
|
|
74
|
+
def create_task(self, *, task_type: str, trigger_at: Optional[float] = None,
|
|
75
|
+
interval_seconds: Optional[float] = None,
|
|
76
|
+
cron_expr: Optional[str] = None,
|
|
77
|
+
cron_timezone: str = "Asia/Shanghai",
|
|
78
|
+
callback_data: Any = None,
|
|
79
|
+
label: Optional[str] = None,
|
|
80
|
+
source: Optional[str] = None,
|
|
81
|
+
next_run: float,
|
|
82
|
+
max_runs: int = 0,
|
|
83
|
+
missed_policy: str = "fire_immediately") -> str:
|
|
84
|
+
task_id = uuid.uuid4().hex
|
|
85
|
+
now = time.time()
|
|
86
|
+
|
|
87
|
+
if task_type not in VALID_TYPES:
|
|
88
|
+
raise ValueError(f"Invalid task type: {task_type}, must be one of {VALID_TYPES}")
|
|
89
|
+
if missed_policy not in VALID_MISSED_POLICIES:
|
|
90
|
+
raise ValueError(f"Invalid missed_policy: {missed_policy}, must be one of {VALID_MISSED_POLICIES}")
|
|
91
|
+
|
|
92
|
+
row = {
|
|
93
|
+
"id": task_id,
|
|
94
|
+
"type": task_type,
|
|
95
|
+
"status": "pending",
|
|
96
|
+
"trigger_at": trigger_at,
|
|
97
|
+
"interval_seconds": interval_seconds,
|
|
98
|
+
"cron_expr": cron_expr,
|
|
99
|
+
"cron_timezone": cron_timezone,
|
|
100
|
+
"callback_data": json.dumps(callback_data, ensure_ascii=False) if callback_data is not None else "null",
|
|
101
|
+
"label": label,
|
|
102
|
+
"source": source,
|
|
103
|
+
"created_at": now,
|
|
104
|
+
"last_run": None,
|
|
105
|
+
"next_run": next_run,
|
|
106
|
+
"run_count": 0,
|
|
107
|
+
"max_runs": max_runs,
|
|
108
|
+
"missed_policy": missed_policy,
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
sdk.storage.Table(TABLE_NAME).Insert(row).Execute()
|
|
112
|
+
return task_id
|
|
113
|
+
|
|
114
|
+
def get_task(self, task_id: str) -> Optional[dict]:
|
|
115
|
+
row = sdk.storage.Table(TABLE_NAME).Select("*").Where("id = ?", task_id).ExecuteOne()
|
|
116
|
+
return self._row_to_dict(row)
|
|
117
|
+
|
|
118
|
+
def list_tasks(self, source: Optional[str] = None,
|
|
119
|
+
status: Optional[str] = None,
|
|
120
|
+
task_type: Optional[str] = None) -> List[dict]:
|
|
121
|
+
query = sdk.storage.Table(TABLE_NAME).Select("*")
|
|
122
|
+
conditions = []
|
|
123
|
+
params = []
|
|
124
|
+
|
|
125
|
+
if source is not None:
|
|
126
|
+
conditions.append("source = ?")
|
|
127
|
+
params.append(source)
|
|
128
|
+
if status is not None:
|
|
129
|
+
conditions.append("status = ?")
|
|
130
|
+
params.append(status)
|
|
131
|
+
if task_type is not None:
|
|
132
|
+
conditions.append("type = ?")
|
|
133
|
+
params.append(task_type)
|
|
134
|
+
|
|
135
|
+
if conditions:
|
|
136
|
+
where_clause = " AND ".join(conditions)
|
|
137
|
+
query = query.Where(where_clause, *params)
|
|
138
|
+
|
|
139
|
+
rows = query.OrderBy("next_run").Execute()
|
|
140
|
+
return self._rows_to_dicts(rows)
|
|
141
|
+
|
|
142
|
+
def get_pending_tasks(self) -> List[dict]:
|
|
143
|
+
now = time.time()
|
|
144
|
+
rows = (sdk.storage.Table(TABLE_NAME)
|
|
145
|
+
.Select("*")
|
|
146
|
+
.Where("status = ? AND next_run <= ?", "pending", now)
|
|
147
|
+
.OrderBy("next_run")
|
|
148
|
+
.Execute())
|
|
149
|
+
return self._rows_to_dicts(rows)
|
|
150
|
+
|
|
151
|
+
def get_all_active_tasks(self) -> List[dict]:
|
|
152
|
+
rows = (sdk.storage.Table(TABLE_NAME)
|
|
153
|
+
.Select("*")
|
|
154
|
+
.Where("status = ?", "pending")
|
|
155
|
+
.OrderBy("next_run")
|
|
156
|
+
.Execute())
|
|
157
|
+
return self._rows_to_dicts(rows)
|
|
158
|
+
|
|
159
|
+
def update_task(self, task_id: str, **fields) -> bool:
|
|
160
|
+
if not fields:
|
|
161
|
+
return False
|
|
162
|
+
allowed = {"status", "next_run", "last_run", "run_count", "trigger_at",
|
|
163
|
+
"interval_seconds", "cron_expr", "cron_timezone", "label",
|
|
164
|
+
"callback_data", "max_runs", "missed_policy", "source"}
|
|
165
|
+
updates = {}
|
|
166
|
+
for k, v in fields.items():
|
|
167
|
+
if k in allowed:
|
|
168
|
+
if k == "callback_data" and v is not None:
|
|
169
|
+
v = json.dumps(v, ensure_ascii=False)
|
|
170
|
+
updates[k] = v
|
|
171
|
+
|
|
172
|
+
if not updates:
|
|
173
|
+
return False
|
|
174
|
+
|
|
175
|
+
sdk.storage.Table(TABLE_NAME).Update(updates).Where("id = ?", task_id).Execute()
|
|
176
|
+
return True
|
|
177
|
+
|
|
178
|
+
def mark_completed(self, task_id: str):
|
|
179
|
+
now = time.time()
|
|
180
|
+
self.update_task(task_id, status="completed", last_run=now)
|
|
181
|
+
|
|
182
|
+
def increment_run(self, task_id: str, next_run: Optional[float] = None):
|
|
183
|
+
task = self.get_task(task_id)
|
|
184
|
+
if task is None:
|
|
185
|
+
return
|
|
186
|
+
now = time.time()
|
|
187
|
+
new_count = task.get("run_count", 0) + 1
|
|
188
|
+
updates = {
|
|
189
|
+
"run_count": new_count,
|
|
190
|
+
"last_run": now,
|
|
191
|
+
}
|
|
192
|
+
if next_run is not None:
|
|
193
|
+
updates["next_run"] = next_run
|
|
194
|
+
|
|
195
|
+
max_runs = task.get("max_runs", 0)
|
|
196
|
+
if max_runs > 0 and new_count >= max_runs:
|
|
197
|
+
updates["status"] = "completed"
|
|
198
|
+
|
|
199
|
+
self.update_task(task_id, **updates)
|
|
200
|
+
|
|
201
|
+
def delete_task(self, task_id: str) -> bool:
|
|
202
|
+
sdk.storage.Table(TABLE_NAME).Delete().Where("id = ?", task_id).Execute()
|
|
203
|
+
return True
|
|
204
|
+
|
|
205
|
+
def cancel_task(self, task_id: str) -> bool:
|
|
206
|
+
return self.update_task(task_id, status="cancelled")
|
|
207
|
+
|
|
208
|
+
def pause_task(self, task_id: str) -> bool:
|
|
209
|
+
return self.update_task(task_id, status="paused")
|
|
210
|
+
|
|
211
|
+
def resume_task(self, task_id: str, next_run: float) -> bool:
|
|
212
|
+
return self.update_task(task_id, status="pending", next_run=next_run)
|
|
213
|
+
|
|
214
|
+
def cleanup_completed(self, max_age_seconds: float = 86400 * 7) -> int:
|
|
215
|
+
cutoff = time.time() - max_age_seconds
|
|
216
|
+
rows = (sdk.storage.Table(TABLE_NAME)
|
|
217
|
+
.Select("id")
|
|
218
|
+
.Where("status IN (?, ?) AND created_at < ?", "completed", "cancelled", cutoff)
|
|
219
|
+
.Execute())
|
|
220
|
+
ids = self._rows_to_single(rows, 0)
|
|
221
|
+
count = 0
|
|
222
|
+
for task_id in ids:
|
|
223
|
+
self.delete_task(task_id)
|
|
224
|
+
count += 1
|
|
225
|
+
return count
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ErisPulse-Cron
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: ErisPulse 定时任务调度模块 - 支持一次性/间隔/Cron定时,回调传参,SQLite持久化
|
|
5
|
+
Author: wsu2059q
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: homepage, https://github.com/wsu2059q/ErisPulse-Cron
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Requires-Dist: croniter>=1.3.0
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
Cron/Core.py,sha256=J6s0wHJ0WKysxpjKjsK53JJwCj0KZHOMBvMU5g9YMPk,6563
|
|
2
|
+
Cron/__init__.py,sha256=JwoeoQdhhcY7hAjctiHNX1167xLlXwfy7Qa_z1ftAE8,23
|
|
3
|
+
Cron/scheduler.py,sha256=aBgKdiFBEnYQW8bt23KRUkW01WpUZMBbm99LGfF7h2M,9040
|
|
4
|
+
Cron/store.py,sha256=T0lIRqook94sDct18iljvm-H1BKUQhg0bz0USZM7cho,7854
|
|
5
|
+
erispulse_cron-1.0.0.dist-info/METADATA,sha256=Na7XAjrtTBPsDcoXjnPl_kY69sB9QIpGJmFIociR0dM,322
|
|
6
|
+
erispulse_cron-1.0.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
7
|
+
erispulse_cron-1.0.0.dist-info/entry_points.txt,sha256=K8PRMONPsfv6tbAQ7hlVIi2VZK9wEiIzot--CMLvWPw,36
|
|
8
|
+
erispulse_cron-1.0.0.dist-info/top_level.txt,sha256=z9j1yPvxzxD1L-3cEGsRH6CMaBXUP69Rf6a0J0isVxM,5
|
|
9
|
+
erispulse_cron-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
Cron
|