views:

162

answers:

4

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

A: 

Compare the current time to the time you should be running, and if it's later than run and then reset the time.

Ignacio Vazquez-Abrams
+1  A: 

use settimer with ITIMER_REAL and have your function be called by the handler for SIGALARM.

Moron
I read this somewhere: "You shouldn't count on the signal arriving precisely when the timer expires. In a multiprocessing environment there is typically some amount of delay involved." Is there way to trigger function call precisely in time? I have the same daemon running on several different machines, and I would like to have them trigger the function call at the time (within a second)
bob
A: 

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!
slebetman
+1  A: 

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
dtmilano