Use when cron jobs, Kubernetes CronJobs, BullMQ repeat jobs, Sidekiq schedules or any time-based job need tests: cron expression validation, DST and leap-day edge cases, catch-up after downtime, overlapping-run locks with stale-lock recovery, and time zones.
87%
Does it follow best practices?
Run evals on this skill
Adds up to 20 points to the overall score
Passed
No findings from the security scan
Cron jobs are universally underspecified. Most teams ship cron expressions, never test them, and discover bugs when DST or a leap day rolls around. This skill is a build-an-X workflow for authoring cron-job tests - a checklist + per-pattern test recipes, not a single tool.
apiVersion: batch/v1)repeat jobs (Step 6 of bullmq-tests)croniter (or a language-native
validator), parametrizing known-good and known-bad expressions (Step 1).croniter against zoneinfo and assert them (Step 2).startingDeadlineSeconds, BullMQ drop (Step 3).croniter(..., tz=...) or k8s
.spec.timeZone (Step 6).The 5-field standard:
┌─── minute (0-59)
│ ┌─── hour (0-23)
│ │ ┌─── day of month (1-31)
│ │ │ ┌─── month (1-12 or JAN-DEC)
│ │ │ │ ┌─── day of week (0-6 or SUN-SAT; 0 and 7 both = Sunday)
│ │ │ │ │
* * * * *Six-field variants (Quartz, BullMQ pattern mode) prepend a seconds field.
Default: croniter (Python) - it both validates expressions and computes next-run times, which Steps 2 + 6 below depend on. Use a language-native validator when the test suite isn't Python: cron-validator (Node), CronExpression.isValidExpression() (Java/Quartz), or crontab.guru for ad-hoc human checks.
Test pattern:
from croniter import croniter
import pytest
@pytest.mark.parametrize("expr", [
"0 3 * * *", # daily 03:00
"0 0 1 * *", # monthly on the 1st
"*/15 * * * *", # every 15 min
"0 9 * * 1-5", # weekdays at 09:00
])
def test_cron_expression_is_valid(expr):
assert croniter.is_valid(expr)The two highest-risk dates per year:
Test pattern:
from croniter import croniter
from datetime import datetime
from zoneinfo import ZoneInfo
def test_daily_2am_handles_dst_spring_forward():
# 2026 spring-forward in US/Eastern: Mar 8, 2:00 AM EST → 3:00 AM EDT
base = datetime(2026, 3, 8, 1, 0, tzinfo=ZoneInfo("US/Eastern"))
next_run = croniter("0 2 * * *", base).get_next(datetime)
# croniter's behavior: skip the missing 02:00 hour, return 03:00 EDT
assert next_run.hour == 3
assert next_run.utcoffset().total_seconds() == -4 * 3600 # EDTRecommendation: schedule cron jobs in UTC where possible to avoid DST entirely. If local time is required, document the DST-handling decision in the cron-job code.
When the host / cluster is down at the scheduled time, what happens?
anacron for
catch-up.).spec.startingDeadlineSeconds
controls how late a missed run may start (per Kubernetes
CronJob spec).Test pattern (Kubernetes CronJob):
# CronJob with deadline
spec:
schedule: "0 3 * * *"
startingDeadlineSeconds: 300 # if not started within 5 min, skip
concurrencyPolicy: Forbid # don't overlap with previous run# Test: simulate cluster downtime (drain nodes), then re-enable past 03:00 + 5min
# → CronJob controller should NOT trigger the missed run (past deadline)
# → CronJob controller SHOULD trigger if re-enabled past 03:00 but within deadlineFor OSS test patterns, use kind (Kubernetes IN Docker) clusters in
CI to verify CronJob behavior.
If a long-running job overlaps its next scheduled run, both may execute in
parallel (Unix cron), a concurrency policy may block / replace the new run
(Kubernetes .spec.concurrencyPolicy), or workers may process repeat-jobs in
parallel (BullMQ). Guard it with a lock. Per-scheduler semantics and the
fcntl lock test pattern are in
references/lock-patterns.md.
A long-held lock from a crashed job blocks all future runs. Detect it with a time-based staleness check, remove it, and re-acquire. Test pattern in references/lock-patterns.md.
def test_cron_runs_at_specified_tz():
base = datetime(2026, 5, 6, 0, 0, tzinfo=ZoneInfo("UTC"))
# Schedule 09:00 in Tokyo (UTC+9):
cron = croniter("0 9 * * *", base, tz="Asia/Tokyo")
next_run = cron.get_next(datetime)
# Should be 00:00 UTC the same day:
assert next_run.astimezone(ZoneInfo("UTC")).hour == 0For Kubernetes CronJobs, schedule timezone is set via
.spec.timeZone (Kubernetes 1.27+).
Day of month and day of week together. "If both fields are
restricted (i.e., do not contain the "*" character), the command will be
run when either field matches the current time" (crontab(5)).
0 9 1 * 1 is therefore "the 1st of every month and every Monday", not
"the first Monday". Schedule one field and check the other in code:
schedule: "0 9 * * 1" # every Monday 09:00
timeZone: "Asia/Nicosia"def is_first_monday(today: date) -> bool:
return today.weekday() == 0 and today.day <= 7Test the expression's next fire times with a parser (croniter) and the
guard with dates from several months, including a month that starts on
a Monday.
Time zone goes in timeZone. "Specifying a timezone using CRON_TZ or
TZ variables inside .spec.schedule is not officially supported"; use
.spec.timeZone (Kubernetes CronJob).
Two Jobs or none. A CronJob creates a Job "approximately once per
execution time"; "there are certain circumstances where two Jobs might
be created, or no Job might be created" (Kubernetes CronJob).
concurrencyPolicy: Forbid stops overlap, not duplicates, so the job
itself must claim its period before doing work:
def run_monthly_digest(db, today: date) -> bool:
if not is_first_monday(today):
return False
claimed = db.execute(
"INSERT INTO job_runs (job, period) VALUES ('digest', %s) "
"ON CONFLICT (job, period) DO NOTHING RETURNING 1",
[today.strftime("%Y-%m")]).fetchone()
if claimed is None:
return False # a second Job for the same month sends nothing
send_digests(db)
return TrueTest: call it twice for the same month and assert one send; call it on the 1st when the 1st is not a Monday and assert no send.
Missed runs. "If there are more than 100 missed schedules, then it
does not start the Job and logs the error"; with
startingDeadlineSeconds set, the controller only counts misses inside
that window (Kubernetes CronJob). Set it so a run missed
during an outage still starts late (for a monthly job, hours or days),
and alert when a period has no job_runs row.
Job Schedulers "replace "repeatable jobs", and are available in v5.16.0
and onwards" (BullMQ job schedulers). queue.add(name, data, { repeat }) called on every boot creates a second repeatable job whenever
the pattern changes; upsertJobScheduler "ensures the scheduler is
updated or created without duplications", keyed by its id:
await queue.upsertJobScheduler(
'daily-report', // stable id
{ pattern: '0 7 * * *', tz: 'Europe/Berlin' }, // local time across DST
{ name: 'daily-report', data: { kind: 'sales' } },
);Migrate once: list existing schedulers with queue.getJobSchedulers()
and remove stale ones with queue.removeJobScheduler(key)
(manage job schedulers). Tests:
getJobSchedulers() returns one entry with the new pattern and tz;For each cron job in scope:
idempotency-test-author)A daily digest email is scheduled 0 2 * * * in US/Eastern - the exact 02:00
window that spring-forward DST removes. Three tests lock it down:
croniter.is_valid("0 2 * * *") returns True
(Step 1).croniter("0 2 * * *", base).get_next(datetime) from
2026-03-08 01:00 US/Eastern returns 03:00 EDT at a -4h offset; the missing
hour is skipped, not fired twice (Step 2).fcntl lock, and
test_lock_prevents_overlap asserts a second concurrent acquire exits
(references/lock-patterns.md).The suite proves the schedule is valid, survives the DST gap without zero- or double-firing, and cannot overlap itself. The follow-up action is to move the schedule to UTC so the DST window never applies (Step 2 recommendation).
| Anti-pattern | Why it fails | Fix |
|---|---|---|
| Trust the cron expression without parsing it | Typos like * * * 13 * (invalid month) silently never trigger | Validate with croniter / cron-validator (Step 1) |
| Schedule in local time without documenting TZ | DST + cross-region deployments cause silent shifts | UTC where possible (Step 2) |
| No overlap protection on long-running jobs | Concurrent runs corrupt state | Lock pattern + concurrency policy (Step 4) |
| Locks without staleness recovery | Crashed job blocks all future runs forever | Time-based stale check (Step 5) |
| No alerting on missed runs | Job silently stops; discovered weeks later | Synthetic-monitor + heartbeat (cross-ref synthetic-monitor-author) |
zoneinfo
in Python 3.9+) for reproducibility.bullmq-tests Step 6 - BullMQ
repeat-job patternsidekiq-tests - Sidekiq schedulingidempotency-test-author -
critical companion (idempotency is the only safe answer to
duplicate runs)synthetic-monitor-author - heartbeat-based missed-run alerting