Why does cron only offer minute granularity?

It feels like there are use cases for things you'd want to run once every 5 seconds, twice a minute, etc, but these are impossible with cron. Why hasn't second-level cron granularity been built into modern operating systems? (Or has it and I don't know..?)


Solution 1:

In short, compatibility.

The format that crontab uses is described in minute detail as part of the POSIX Specification. Linux distros are generally not 100% fully compliant with the POSIX specs, but they are generally very close, as most of the things in the POSIX spec are the parts of a Unix-like machine that developers take for granted as existing. As far as Cron goes, the Linux Standard Base specifies rather directly that it should behave as per POSIX.

Certainly, individual distros might choose to modify the Cron they use, but Adding second-level granularity would require another field, making the new crontab effectively completely incompatible with virtually everything that uses Cron.

But, pointing out that it's for compatibility doesn't really give us any insight as to why it's granular only at the minute level. So, why has Cron always used minute-level granularity?

Well, I wasn't exactly there (nor even born at the time), but I suspect it's due to the way Cron was first implemented.

The cron in Version 7 Unix, written by Brian Kernighan, was a system service (later called daemons) invoked from /etc/inittab when the operating system entered multi-user mode. Its algorithm was straightforward:

1.Read /usr/etc/crontab

2.Determine if any commands must run at the current date and time, and if so, run them as the superuser, root.

3.Sleep for one minute

4.Repeat from step 1.

A Cron implementation based on a sleep loop would almost certainly break down miserably with finer granularity than one minute; as it is, Cron had to be rewritten to use more efficient methods in order to be able to handle loads on the order of 100 users. One-second granularity would be even worse than that at just two users.

So, because the program initially couldn't handle it, and because the format has continued on, and because changing it would be a rather large compatibility break, it's very likely that cron will never support sub-minute granularity. Especially because, as MichaelT pointed out in the comments, use of sleep commands can easily create the desired behavior, without the need for changes to Cron itself.