7

I want to know how cron works internally. Does the process keep checking the current time in an infinite while loop (thus continually consuming CPU cycles)? Or does some function generate an interrupt and notifies the cron daemon ?

9

I once read the vixie-cron source code and had to be hospitalized. However if you're looking for "some function generate an interrupt" at a time in the future, you should investigate the alarm(2) syscall. It asks the kernel to send you the signal SIGALRM at a scheduled time, which you can then catch. In the mean time, your process can do something else, or sleep(), like I did in the hospital.

| improve this answer | |
  • 4
    Upvoted for humor. – 4ae1e1 Jul 22 '14 at 16:03
6

I'm sure there are many variations, the way it works in dcron (aka Dillon's cron daemon) is that it sleeps for up to 60 seconds at a time, it tries to synchronise this by sleeping less if needed so as to wake up at 00 seconds of each minute.

It uses sleep() which puts the process to sleep (unless a signal occurs) without using CPU. When it wakes, it checks for a file cron.update (created by crontab editing). It recreates its run queue if required, runs the expected tasks, and sleeps again.

At least one cron daemon (fcrond) uses a signal sent by crontab editing to the cron daemon instead of a sleep/check approach.

I've never seen a crond that runs things more frequently than once per-minute, so they are usually quite light on resources.

On Linux, if you look in /proc at things like bytes read/written or iowait for crond you may see that it has relatively high usage, this is because it ends up accounting for all the child processes that it starts, e.g. on CentOS 5.x:

# grep "^[rw]" /proc/`pgrep crond`/io
rchar: 153463658151
wchar: 91095820045
read_bytes: 44480745472
write_bytes: 2261389312

(thanks to scheduled package updates, and ASLR/pre-link tasks in this case)

See also https://stackoverflow.com/questions/3982957/how-does-cron-internally-schedule-jobs .

| improve this answer | |
  • 1
    At least one exception exists: fcron does not wake up each minute just to check whether it has something to do. “Then, fcron calculates the time and date of each job's next execution, and determines how long it has to sleep, and sleeps for this amount of time.” – man fcron – manatwork Feb 9 '13 at 13:20
  • Nice one, not familiar with fcrond, just checked the source: it invokes a helper to HUP the crond. – mr.spuratic Feb 9 '13 at 21:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.