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 time
import uuid
from datetime import datetime
from pathlib import Path
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:
try:
from croniter import croniter
cron = croniter(schedule.expr, time.time())
next_time = cron.get_next()
return int(next_time * 1000)
from zoneinfo import ZoneInfo
base_time = time.time()
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:
return None