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.
cron-quickstart.salam
import cron
const ZONE := "Invalid/Nowhere"const OFF := 210const AFTER := 1792800300asi64funcshow(spec: str):
e := cron.Parse(spec)
println spec, e.ok, cron.Next(e, AFTER, ZONE, OFF)
endfuncmain:
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)
end
Times 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.
Weekdays 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.
Run 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.
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".
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.
next daily 1792837800
next weekly 1792980015
next limited 1792800305
found true tagged true
launch 2
removed by tag 1 left 1
Controlling 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.
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.
•
Stop is 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.
Parses five fields, or six with a leading seconds field, or a macro such as @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.
cron-Parse.salam
import cron
const ZONE := "Invalid/Nowhere"const OFF := 210const AFTER := 1792800300asi64funcshow(spec: str):
e := cron.Parse(spec)
println spec, e.ok, cron.Next(e, AFTER, ZONE, OFF)
endfuncmain:
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)
end