scheme shell
about
download
support
resources
docu
links
 
scsh.net

Run With Timer

The procedure `run-with-timer' bellow, after the Emacs function with the same name, allows to perform an action after a delay of SECS seconds. Call THUNK every SECS seconds then, if REPEAT? is a true value.

It returns a timer object, which you can use with `cancel-timer!'.

Sample usage:

   (define *timer* 
     (run-with-timer 3 #t (lambda ()
                            (display "Hello!")
                            (newline))))

(cancel-timer! *timer*)

The code:

   ;;; Timer for Delayed Execution
   ;;; Emilio C. Lopes <eclig@gmx.net>, 2006-06-30

(define-structure timer (export run-with-timer timer? cancel-timer!)

(open define-record-types threads threads-internal locks scheme)

(begin " ("

(define-record-type timer :timer (make-timer thread) timer? (thread timer-thread))

(define (run-with-timer secs repeat? thunk) (let ((lock (make-lock)) (thread-obj #f) (timeout (* secs 1000))) (obtain-lock lock) (spawn (lambda () (set! thread-obj (current-thread)) (release-lock lock) (let loop () (sleep timeout) (thunk) (if repeat? (loop))))) (obtain-lock lock) (make-timer thread-obj)))

(define (cancel-timer! timer) (terminate-thread! (timer-thread timer)))

))


RunWithTimer - raw wiki source | code snippets archive