Updated 2012-05-23 13:56:24 by aspect

SS 16Dec2004:

A Tcl user had a problem in the Tclers chat with timers and syncronization. The problem is to execute some code every 30 minutes, but syncronized with the real clock of the comuter. So at 01:00, 01:30, 02:00, and so on.

The following procedure should do just it, but it's possible to change the timer period modifing the 'every' variable that's hardcoded to 1800 in this example.

I didn't tested the code a lot... so if you need to use it in a critical application please do some test.
 proc cron {{opt {}}} {
     set every 1800
     if {$opt eq {}} {
        # Do the work you need every $every seconds
        puts [clock format [clock seconds]]
     }
     after [expr {($every-([clock seconds] % $every))*1000}] cron
 }

 cron -init
 vwait forever

ABU 26-may-2005

Here is yet another implementation SyncTimer.

Added features:

  • Timers can be stopped and restarted
  • timers can be kept in sync with system-clock
  • timers can be started after a given amount
 # example
 set t1  [SyncTimer::every "1 hour" "00:30:00" {puts "every hour at the half-hour"}]
 $t1 start

See also the page for every, which shows the evolution of the trivial one-line implementation into a full sibling of after, with valuable discussion along the way.