Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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 ?

share|improve this question
add comment

2 Answers

up vote 1 down vote accepted

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.

share|improve this answer
add comment

I'm sure there are many variations, the way it works in dcron is that it sleeps for up to 60 seconds at a time, it tries to synchronise this by sleeping less if needed to wake up at 00 seconds.

It uses sleep() which put 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.

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

Under 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/prelink tasks in this case)

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

share|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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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