Next: , Previous: Threading, Up: Top


13 Timers

SBCL supports a system-wide event scheduler implemented on top of setitimer that also works with threads but does not require a separate scheduler thread.

The following example schedules a timer that writes “Hello, word” after two seconds.

     (schedule-timer (make-timer (lambda ()
                                   (write-line "Hello, world")
                                   (force-output)))
                     2)

It should be noted that writing timer functions requires special care, as the dynamic environment in which they run is unpredictable: dynamic variable bindings, locks held, etc, all depend on whatever code was running when the timer fired. The following example should serve as a cautionary tale:

     (defvar *foo* nil)
     
     (defun show-foo ()
       (format t "~&foo=~S~%" *foo*)
       (force-output t))
     
     (defun demo ()
       (schedule-timer (make-timer #'show-foo) 0.5)
       (schedule-timer (make-timer #'show-foo) 1.5)
       (let ((*foo* t))
         (sleep 1.0))
       (let ((*foo* :surprise!))
         (sleep 2.0)))

13.1 Timer Dictionary

— Structure: sb-ext:timer

Class precedence list: timer, structure-object, t

Timer type. Do not rely on timers being structs as it may change in future versions.

— Function: sb-ext:make-timer function &key name thread

Create a timer object that's when scheduled runs function. If thread is a thread then that thread is to be interrupted with function. If thread is t then a new thread is created each timer function is run. If thread is nil then function can be run in any thread. When thread is not t, interrupt-thread is used to run function and the ordering guarantees of interrupt-thread also apply here. function always runs with interrupts disabled but with-interrupts is allowed.

— Function: sb-ext:timer-name timer

Return the name of timer.

— Function: sb-ext:timer-scheduled-p timer &key delta

See if timer will still need to be triggered after delta seconds from now. For timers with a repeat interval it returns true.

— Function: sb-ext:schedule-timer timer time &key repeat-interval absolute-p

Schedule timer to be triggered at time. If absolute-p then time is universal time, but non-integral values are also allowed, else time is measured as the number of seconds from the current time. If repeat-interval is given, timer is automatically rescheduled upon expiry.

— Function: sb-ext:unschedule-timer timer

Cancel timer. Once this function returns it is guaranteed that timer shall not be triggered again and there are no unfinished triggers.

— Function: sb-ext:list-all-timers

Return a list of all timers in the system.