fix(cron): add timezone support for accurate next run time calculation

When schedule.tz is present, use the specified timezone to calculate the next execution time, ensuring scheduled tasks trigger correctly across different timezones.
This commit is contained in:
Ahwei 2026-02-14 10:23:54 +08:00
parent f821e95d3c
commit 153c83e340

View File

@ -4,6 +4,7 @@ import asyncio
import json import json
import time import time
import uuid import uuid
from datetime import datetime
from pathlib import Path from pathlib import Path
from typing import Any, Callable, Coroutine from typing import Any, Callable, Coroutine
@ -30,9 +31,18 @@ def _compute_next_run(schedule: CronSchedule, now_ms: int) -> int | None:
if schedule.kind == "cron" and schedule.expr: if schedule.kind == "cron" and schedule.expr:
try: try:
from croniter import croniter from croniter import croniter
cron = croniter(schedule.expr, time.time()) from zoneinfo import ZoneInfo
next_time = cron.get_next() base_time = time.time()
return int(next_time * 1000) if schedule.tz:
tz = ZoneInfo(schedule.tz)
base_dt = datetime.fromtimestamp(base_time, tz=tz)
cron = croniter(schedule.expr, base_dt)
next_dt = cron.get_next(datetime)
return int(next_dt.timestamp() * 1000)
else:
cron = croniter(schedule.expr, base_time)
next_time = cron.get_next()
return int(next_time * 1000)
except Exception: except Exception:
return None return None