(util timer) - Timer

Library (util timer)

This library provides timer functionality.

Timer is the mechanism to trigger an event on specified time.

The following describes how to use;

(import (util timer))

(let ((timer (make-timer)))
  (timer-start! timer) ;; start timer
  ;; execute given thunk starting after 1000ms and each 1000ms
  (timer-schedule! timer (lambda () (display "timer!") (newline)) 1000 1000)
  ;; do something
  (timer-cancel! timer))

A timer is kind of task queue running on a timer thread. Once it's started, then it waits until its queue is not empty or the first task reaches the configured time. The tasks are executed sequentially however its order is not reliable if there are multiple tasks queued on the same time.

Function timer? obj

Returns #t if obj is a timer object, otherwise #f.

Function make-timer :key error-handler

Creates a timer object.

If keyword argument error-handler is specified, then it must be a procedure accepts one argument. The error-handler is called when timer procedure raises an error. If this is not specified, then timer stops when one of the tasks raised an error.

Function timer-state timer

Returns the state of given timer. The possible states are the followings:

created

The timer is created and not executed yet.

running

The timer is running.

stopped

The timer is stopped (can be resumed).

cancelled

The timer is cancelled (cannot be resumed).

Function timer-start! timer

Starts the given created state timer.

If the given timer's state is stopped, then this procedure resumes the given timer.

If the timer state is not created or stopped, then &assertion is raised.

Function timer-stop! timer

Stops the given time.

Function timer-cancel! timer

Cancel the given time. If one of the tasks raised an error and no error handler is specified, then this procedure will re-raise the error.

Once the timer is cancelled, then this timer is completely destroyed.

Function timer-schedule! timer thunk first :optional (period 0)

Schedules a timer task.

first can be time object or exact integer. If this is time object, then the timer executes the thunk with given time (absolute time). If this is an exact integer, then the timer executes the thunk after the given number milliseconds from current time.

Optional argument period specifies if the thunk is periodically executed or not. 0 is not periodical task.

The returning value is an ID of scheduled task. This is needed for timer-remove! and timer-exists? procedures.

Function timer-reschedule! timer timer-id first :optional (period 0)

Reschedules the timer task associated with timer-id and returns _timer-id_The first and period are the same as timer-schedule!.

Function timer-remove! timer id

Removes given id task from the timer.

Function timer-exists? timer id

Returns #t if given id task exists in the timer, otherwise #f.