cron
Cron expressions with optional seconds, interval, daily, weekly, monthly and one-time jobs, tags, limits and hooks, each job on its own thread.
import cron
cron parses the usual five-field cron expression (or six, with a leading seconds field), matches it against a time, computes the next matching moment, and runs registered jobs on a one-second tick. It is a library, not a service: it runs inside your program, uses your program's threads and stops when your program stops.
The five fields are minute, hour, day of month, month and day of week, in that order. Each field accepts *, a number, a range a-b, a list a,b,c, and a step */n or a-b/n. Months and weekdays also accept three-letter English names such as jan and mon. As in Vixie cron, when both day fields are restricted a time matches either of them; when one is *, both must match.
*/15 * * * * every quarter hour
0 9-17 * * mon-fri every hour from 9 to 17 on weekdays
30 2 1 * * at 02:30 on the first day of every month
0 0 29 feb * on February 29
The macros @yearly, @annually, @monthly, @weekly, @daily, @midnight and @hourly expand to the usual five fields.
Parsing and the next run
Parse returns an Expr with ok false when the text is not a valid expression. Check ok before you use it. Next returns the first minute strictly after the given time that matches, in the given time zone, or 0 when it finds none within the scan limit.
import cron
const ZONE := "Invalid/Nowhere"
const OFF := 210
const AFTER := 1792800300 as i64
func show(spec: str):
e := cron.Parse(spec)
println spec, e.ok, cron.Next(e, AFTER, ZONE, OFF)
end
func main:
show("*/20 * * * *")
show("@daily")
show("0 0 29 feb *")
show("nope")
e := cron.Parse("*/5 * * * *")
println cron.MatchFields(e, 15, 10, 1, 1, 0)
println cron.MatchFields(e, 16, 10, 1, 1, 0)
println cron.OffsetSeconds(ZONE, OFF, AFTER)
endTimes are UTC seconds since the epoch. Next asks the zone database for the offset at each candidate minute, so daylight saving changes are handled. When the zone does not exist, every call takes fallback_minutes instead, which is also what the tests use to stay independent of the machine.
Matching a time you already have
MatchFields takes the local minute, hour, day, month and weekday directly, so you can use it on values from your own clock or from a database. MatchesLocal takes a wall-clock instant in seconds, already shifted by the zone offset, and is what the scheduler uses internally.
import cron
func main:
e := cron.Parse("0 9-17 * * mon-fri")
println cron.MatchFields(e, 0, 9, 1, 1, 1)
println cron.MatchFields(e, 30, 9, 1, 1, 1)
println cron.MatchesLocal(e, 1793005200 as i64)
endWeekdays are 0 for Sunday through 6 for Saturday; 7 is accepted and treated as Sunday. MatchFields returns false for an expression whose ok is false.
Zones and offsets
The scheduler keeps one zone for all jobs. SetZone sets its name and the fallback offset in minutes, used when the name cannot be loaded. OffsetSeconds returns the offset of any zone at an instant, which is useful outside the scheduler too.
cron.SetZone("Asia/Tehran", 210)
off := cron.OffsetSeconds("Asia/Tehran", 210, 1700000000 as i64)
println off / (60 as i64)
The default zone is UTC with a fallback of 0. Call SetZone before Run or RunBackground; changing it later affects the next minute, not a job that is already running.
Jobs and the scheduler
Add registers a function under a name and an expression and returns the job id, or -1 when the expression does not parse. A job handler takes the job id as an i64. Register every job before you start the scheduler.
import mem
import time
import cron
mut hits := null as i64*
func tick(id: i64):
atomic_add(hits, 1 as i64)
println "job", id, cron.Name(id as int)
end
func main:
hits = mem.AllocateZeroed(8 as u64) as i64*
cron.SetZone("Invalid/Nowhere", 210)
every := cron.Add("every minute", "* * * * *", tick)
nightly := cron.Add("nightly", "0 3 * * *", tick)
broken := cron.Add("broken", "nope", tick)
println cron.Count(), cron.Name(every), cron.Name(nightly), broken
println cron.IsBusy(every)
started := cron.RunDue(1792800300 as i64)
mut waited := 0
until atomic_load(hits) == (0 as i64) or waited >= 200:
time.Sleep(10)
waited++
end
println "started", started, "hits", atomic_load(hits)
println cron.IsBusy(every)
cron.RunBackground()
cron.Stop()
endRun blocks and fires the jobs that are due once a minute; RunBackground runs the same loop on its own thread and returns at once. RunDue fires what is due at the given time without waiting for the next minute, which is what a test or a manual tick uses. In every form a job that is still running from an earlier firing is skipped, not queued, so a slow job cannot pile up.
Count, Name and IsBusy inspect the table. Stop asks the loop to end after the current job; it does not wait for a running job, and it can be called from a signal handler or another thread.
cron.SetZone("UTC", 0)
cron.Add("cleanup", "0 3 * * *", cleanup)
cron.RunBackground()
time.Sleep(60000)
cron.Stop()
Seconds
A sixth field in front of the minute gives second resolution: */10 * * * * * fires every ten seconds and 0 30 9 * * mon at 09:30:00 on Mondays. With five fields nothing changes: the job fires once in the matching minute.
Setting a time without cron syntax
Most schedules are a clock time, so they have helpers that take "HH:MM" or "HH:MM:SS".
cron.DailyAt("report", "10:30", report)
cron.WeeklyAt("backup", "mon-fri", "02:00", backup)
cron.MonthlyAt("invoice", 1, "08:00", invoice)
cron.Every("heartbeat", 30, beat)
cron.EveryBetween("poll", 20, 40, poll)
cron.Once("launch", 1792900000 as i64, launch)
All of them return the job id, or -1 when the time does not parse. Every counts from now; EveryBetween picks a random gap between its two bounds each time, which spreads load.
import mem
import time
import cron
mut hits := null as i64*
func tick(_id: i64):
atomic_add(hits, 1 as i64)
end
func wait():
mut waited := 0
until atomic_load(hits) == (0 as i64) and waited < 200:
time.Sleep(10)
waited++
end
repeat cron.Total() in i:
until cron.IsBusy(i) and waited < 400:
time.Sleep(10)
waited++
end
end
end
func main:
hits = mem.AllocateZeroed(8 as u64) as i64*
cron.SetZone("Invalid/Nowhere", 0)
daily := cron.DailyAt("report", "10:30", tick)
weekly := cron.WeeklyAt("backup", "mon-fri", "02:00:15", tick)
cron.SetTags(weekly, "ops,nightly")
cron.Once("launch", 1792900000 as i64, tick)
limited := cron.Add("limited", "*/5 * * * * *", tick)
cron.Limit(limited, 1)
println "next daily", cron.NextRun(daily, 1792800300 as i64)
println "next weekly", cron.NextRun(weekly, 1792800300 as i64)
println "next limited", cron.NextRun(limited, 1792800300 as i64)
println "found", cron.Find("backup") == weekly, "tagged", cron.HasTag(weekly, "ops")
println "launch", cron.RunDue(1792900000 as i64)
wait()
println "removed by tag", cron.RemoveByTag("ops"), "left", cron.Count()
endControlling jobs
Ids are never reused. Remove and RemoveByTag retire jobs, Find looks one up by name, and SetTags takes a comma-separated list. Limit stops a job after n runs, StartAt and StopAt bound it in time, FromCompletion counts an interval from the end of a run, and Queue makes a firing that finds the job busy wait instead of being skipped. RunNow runs a job immediately, NextRun reports its next firing, and Runs, LastRun and LastFinished report what happened. OnBefore and OnAfter register one handler each that runs around every job. A handler that wants to report failure calls Fail(id); OnError then runs after that run and Failures counts them. ConcurrencyLimit caps how many jobs run at once; a firing past the cap is skipped. StopWait stops the loop and waits for running jobs up to a timeout in milliseconds.
Compared with gocron
Salam cron covers gocron's schedule kinds and job options, except distribution.
| gocron | Salam cron |
|---|---|
| CronJob(expr, withSeconds) | Add with five or six fields |
| DurationJob, DurationRandomJob | Every, EveryBetween |
| DailyJob, WeeklyJob, MonthlyJob | DailyAt, WeeklyAt, MonthlyAt (interval of 1) |
| OneTimeJob | Once |
| WithName, WithTags | the name argument, SetTags |
| WithLimitedRuns | Limit |
| WithStartAt, WithStopAt | StartAt, StopAt |
| WithIntervalFromCompletion | FromCompletion |
| WithSingletonMode (reschedule or wait) | skip by default, Queue to wait |
| Before and After listeners | OnBefore, OnAfter, Fail with OnError (no panic listener) |
| NextRun, LastRun, RunNow, RemoveJob | NextRun, LastRun, RunNow, Remove |
| WithLocation | SetZone (one zone for all jobs) |
| WithStopTimeout, Shutdown | StopWait |
| WithLimitConcurrentJobs | ConcurrencyLimit (skips, never queues) |
| Distributed elector and locker, monitors, daily or weekly every n | not available |
For a readable clock time, DailyAt("report", "10:30", f) is shorter than gocron's DailyJob(1, NewAtTimes(NewAtTime(10, 30, 0))), and a plain cron string works in both.
What to know
- Resolution is one second, and only for jobs with a six-field expression or an interval. Five-field jobs fire once in their minute.
- Jobs run on their own threads and share the process with you. A panic, a blocking read or a long loop in one job affects the whole program.
Stopis cooperative: the loop checks the flag several times a second, so a job that ignores its own cancellation can keep running.- The package does not persist jobs. If you need them after a restart, store the name and expression yourself and register them again at startup.
- A day-of-month and day-of-week pair that are both restricted matches either field, as in Vixie cron. This is often surprising; prefer a single day field when you can.
Types
Expr
struct Exprok flag.| Name | Type | Description |
|---|---|---|
minutes | i64 = 0 | The minutes of the hour that match, as a bit mask. |
hours | i64 = 0 | The hours of the day that match, as a bit mask. |
days | i64 = 0 | The days of the month that match, as a bit mask. |
months | i64 = 0 | The months that match, as a bit mask. |
weekdays | i64 = 0 | The weekdays that match, as a bit mask; Sunday is bit 0. |
dom_star | bool = true | True when the day-of-month field was *. |
dow_star | bool = true | True when the day-of-week field was *. |
seconds | i64 = 1 | The seconds that match, as a bit mask; only used when with_seconds is true. |
with_seconds | bool = false | True when the text had a leading seconds field. |
ok | bool = false | True when the text parsed; every other function refuses an expression whose ok is false. |
Functions
Parse
func Parse(spec: str): Expr@daily. Returns an expression with ok false on a bad field count, a number out of range, a broken range, a zero step or an unknown name.import cron
const ZONE := "Invalid/Nowhere"
const OFF := 210
const AFTER := 1792800300 as i64
func show(spec: str):
e := cron.Parse(spec)
println spec, e.ok, cron.Next(e, AFTER, ZONE, OFF)
end
func main:
show("*/20 * * * *")
show("@daily")
show("0 0 29 feb *")
show("nope")
e := cron.Parse("*/5 * * * *")
println cron.MatchFields(e, 15, 10, 1, 1, 0)
println cron.MatchFields(e, 16, 10, 1, 1, 0)
println cron.OffsetSeconds(ZONE, OFF, AFTER)
endMatchFields
func MatchFields(e: Expr, minute: int, hour: int, day: int, month: int, weekday: int): boolimport cron
func main:
e := cron.Parse("0 9-17 * * mon-fri")
println cron.MatchFields(e, 0, 9, 1, 1, 1)
println cron.MatchFields(e, 30, 9, 1, 1, 1)
println cron.MatchesLocal(e, 1793005200 as i64)
endMatchesLocal
func MatchesLocal(e: Expr, local: i64): boolThe example for this item is shown with the ones above: cron-Match.salam
OffsetSeconds
func OffsetSeconds(zone: str, fallback_minutes: int, epoch: i64): i64The example for this item is shown with the ones above: cron-Parse.salam
Next
func Next(e: Expr, after: i64, zone: str, fallback_minutes: int): i64after that matches, in UTC seconds, or 0 when none is found within the scan limit.The example for this item is shown with the ones above: cron-Parse.salam
SetZone
func SetZone(name: str, fallback_minutes: int)UTC with 0.The example for this item is shown with the ones above: cron-Parse.salam
Add
func Add(name: str, spec: str, fn: i64): inti64.import mem
import time
import cron
mut hits := null as i64*
func tick(id: i64):
atomic_add(hits, 1 as i64)
println "job", id, cron.Name(id as int)
end
func main:
hits = mem.AllocateZeroed(8 as u64) as i64*
cron.SetZone("Invalid/Nowhere", 210)
every := cron.Add("every minute", "* * * * *", tick)
nightly := cron.Add("nightly", "0 3 * * *", tick)
broken := cron.Add("broken", "nope", tick)
println cron.Count(), cron.Name(every), cron.Name(nightly), broken
println cron.IsBusy(every)
started := cron.RunDue(1792800300 as i64)
mut waited := 0
until atomic_load(hits) == (0 as i64) or waited >= 200:
time.Sleep(10)
waited++
end
println "started", started, "hits", atomic_load(hits)
println cron.IsBusy(every)
cron.RunBackground()
cron.Stop()
cron.Run()
endEvery
func Every(name: str, seconds: int, fn: i64): intimport mem
import time
import cron
mut hits := null as i64*
func tick(_id: i64):
atomic_add(hits, 1 as i64)
end
func wait():
mut waited := 0
until atomic_load(hits) == (0 as i64) and waited < 200:
time.Sleep(10)
waited++
end
repeat cron.Total() in i:
until cron.IsBusy(i) and waited < 400:
time.Sleep(10)
waited++
end
end
end
func main:
hits = mem.AllocateZeroed(8 as u64) as i64*
cron.SetZone("Invalid/Nowhere", 0)
daily := cron.DailyAt("report", "10:30", tick)
weekly := cron.WeeklyAt("backup", "mon-fri", "02:00:15", tick)
cron.SetTags(weekly, "ops,nightly")
cron.Once("launch", 1792900000 as i64, tick)
limited := cron.Add("limited", "*/5 * * * * *", tick)
cron.Limit(limited, 1)
println "next daily", cron.NextRun(daily, 1792800300 as i64)
println "next weekly", cron.NextRun(weekly, 1792800300 as i64)
println "next limited", cron.NextRun(limited, 1792800300 as i64)
println "found", cron.Find("backup") == weekly, "tagged", cron.HasTag(weekly, "ops")
println "launch", cron.RunDue(1792900000 as i64)
wait()
println "removed by tag", cron.RemoveByTag("ops"), "left", cron.Count()
endEveryBetween
func EveryBetween(name: str, lo: int, hi: int, fn: i64): intThe example for this item is shown with the ones above: cron-Jobs.salam
Once
func Once(name: str, at: i64, fn: i64): intThe example for this item is shown with the ones above: cron-Jobs.salam
DailyAt
func DailyAt(name: str, at: str, fn: i64): int"HH:MM" or "HH:MM:SS" in the scheduler zone. Returns -1 when the time does not parse.The example for this item is shown with the ones above: cron-Jobs.salam
WeeklyAt
func WeeklyAt(name: str, days: str, at: str, fn: i64): int"mon-fri") at a clock time.The example for this item is shown with the ones above: cron-Jobs.salam
MonthlyAt
func MonthlyAt(name: str, day: int, at: str, fn: i64): intThe example for this item is shown with the ones above: cron-Jobs.salam
Count
func Count(): intThe example for this item is shown with the ones above: cron-Schedule.salam
Total
func Total(): intName
func Name(id: int): strThe example for this item is shown with the ones above: cron-Schedule.salam
Find
func Find(name: str): intThe example for this item is shown with the ones above: cron-Jobs.salam
IsBusy
func IsBusy(id: int): boolThe example for this item is shown with the ones above: cron-Schedule.salam
Remove
func Remove(id: int)The example for this item is shown with the ones above: cron-Jobs.salam
SetTags
func SetTags(id: int, tags: str)The example for this item is shown with the ones above: cron-Jobs.salam
HasTag
func HasTag(id: int, tag: str): boolThe example for this item is shown with the ones above: cron-Jobs.salam
RemoveByTag
func RemoveByTag(tag: str): intThe example for this item is shown with the ones above: cron-Jobs.salam
Limit
func Limit(id: int, n: int)The example for this item is shown with the ones above: cron-Jobs.salam
StartAt
func StartAt(id: int, at: i64)The example for this item is shown with the ones above: cron-Jobs.salam
StopAt
func StopAt(id: int, at: i64)The example for this item is shown with the ones above: cron-Jobs.salam
FromCompletion
func FromCompletion(id: int)The example for this item is shown with the ones above: cron-Jobs.salam
Queue
func Queue(id: int)The example for this item is shown with the ones above: cron-Jobs.salam
OnBefore
func OnBefore(fn: i64)OnAfter
func OnAfter(fn: i64)Fail
func Fail(id: i64)OnError
func OnError(fn: i64)Fail.Failures
func Failures(id: int): i64Fail.ConcurrencyLimit
func ConcurrencyLimit(n: int)Runs
func Runs(id: int): i64LastRun
func LastRun(id: int): i64LastFinished
func LastFinished(id: int): i64NextRun
func NextRun(id: int, after: i64): i64The example for this item is shown with the ones above: cron-Jobs.salam
RunDue
func RunDue(now: i64): intThe example for this item is shown with the ones above: cron-Schedule.salam
RunNow
func RunNow(id: int): boolThe example for this item is shown with the ones above: cron-Jobs.salam
Run
func Run()Stop is called.The example for this item is shown with the ones above: cron-Schedule.salam
RunBackground
func RunBackground()The example for this item is shown with the ones above: cron-Schedule.salam
Stop
func Stop()The example for this item is shown with the ones above: cron-Schedule.salam
StopWait
func StopWait(timeout_ms: int)