call function at specific time intervals in Linux
Question
What is the best way to call a function inside a Linux daemon at specific time intervals, and specific time (e.g. at 12am every day, call this function). I'm not referring to calling a process with crontab, but a function within a long running daemon.
Thanks
Solution
use settimer with ITIMER_REAL and have your function be called by the handler for SIGALARM.
OTHER TIPS
From your question tags I understand you are running a shell daemon. So my suggestion is to use crontab, as it is already waiting to be used, to signal your daemon.
In your shell daemon you need a signal handler
handler() {
echo "$(date): doing something special" >> $LOG
}
you have to trap a signal, SIGALRM in this example
trap handler ALRM
and in your crontab send the signal, assuming your daemon is daemon.sh
0 0 * * * killall -s SIGALRM daemon.sh
Compare the current time to the time you should be running, and if it's later than run and then reset the time.
My favourite trick is:
- sleep and wake every Nth seconds (I personally prefer either every second or every 10 seconds)
- when woken up check the time and check to see if I need to run anything
- rinse, repeat...
How you do this depends on your language. In tcl I would do something like:
proc scheduler {} {
global task_list
set now [clock format [clock seconds] -format "%H:%M"]
foreach task $task_list {
lassign $task_list time task
if {$time == $now} {
apply $task
}
}
after 1000 scheduler ;# repeat after 1 second
}
scheduler ;# GO!