Scheduled Jobs and Time Zones: The Midnight Bug I Keep Seeing
说明与用途
使用 IANA 时区定义业务日,在该时区计算报告窗口,转换为 UTC 进行查询,避免在午夜附近触发 cron,并编写四个冻结时间的测试,以消除与 DST 相关的午夜错误。
问题
Cron jobs scheduled at midnight run in UTC, causing reports to use the wrong local day and month due to daylight saving and offset changes.
结果
Implementing explicit business‑zone windows and four edge‑case tests eliminates midnight‑related reporting bugs caused by UTC scheduling and DST shifts.
工作流
- 1. Decide and record the business time zone as an IANA name (e.g., Europe/Berlin).
- 2. Store the zone string in configuration.
- 3. In job code, convert current UTC time to the business zone, subtract one day, snap to start of day, and compute end of day. 4. Convert start and end instants back to UTC for database queries.
- 5. Schedule the cron trigger in UTC, preferably after midnight local time (e.g., 03:00 local).
- 6. Write four unit tests with a frozen clock: midnight, month boundary, spring‑forward, fall‑back.
- 7. Run tests to ensure window boundaries are correct across DST transitions.
- 8. Deploy job with confidence that reporting windows are accurate.
- 9. Monitor for any future DST changes and re‑run tests if necessary.
证据
Cron runs in UTC by default, so a "midnight" job can fire on the wrong local day
Define the business day explicitly with a timezone string, never a UTC offset
Test the four edge cases: midnight, month boundary, spring-forward, fall-back
- 记录日期: 2026-10-21T22:11:23.162Z