Find a repeating schedule interval with lcm
Also published in our Blogger archive.
Recurring jobs align again after a number of minutes that is a multiple of every job interval. The smallest such positive interval is the least common multiple. Python 3.9 introduced math.lcm(), which accepts multiple integer arguments and returns their least common multiple.
The example models three jobs scheduled every 14, 20, and 30 minutes from the same starting instant. math.lcm(*intervals) calculates 420 minutes, so all three schedules next align seven hours after that shared start. The assertions first confirm the expected interval and then verify that 420 has no remainder when divided by each job interval. Output reports the result in both minutes and hours.
This arithmetic assumes fixed integer-minute periods and a shared reference point. It does not calculate calendar scheduling. Time zones, daylight-saving transitions, missed executions, retry policies, job duration, and independent start times all require additional scheduling logic. Zero also has special meaning: if any lcm() argument is zero, the result is zero, which should not be interpreted as a recurring interval without an explicit rule in the application. Very large or relatively prime intervals can produce a large alignment time, even though Python integers themselves can represent it. The assertions demonstrate divisibility for this synthetic schedule, not that a job system will execute reliably.
See the official math.lcm documentation for its integer and zero-argument behavior.
AI assistance disclosure: This article was drafted with AI assistance and should be reviewed against the scheduling system’s semantics.
import math
intervals_minutes = (14, 20, 30)
alignment_minutes = math.lcm(*intervals_minutes)
alignment_hours = alignment_minutes // 60
assert alignment_minutes == 420
assert all(alignment_minutes % interval == 0 for interval in intervals_minutes)
assert alignment_hours == 7
print(f"next alignment: {alignment_minutes} minutes")
print(f"next alignment: {alignment_hours} hours")
next alignment: 420 minutes
next alignment: 7 hours