1

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

Valentin Rocher
  • 11,667
  • 45
  • 59
bob
  • 1,941
  • 6
  • 26
  • 36

4 Answers4

1

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

  • 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 Jan 28 '10 at 14:00
1

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
Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134
0

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
  • 776,304
  • 153
  • 1,341
  • 1,358
0

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
  • 109,858
  • 19
  • 140
  • 171