Timers in OCaml

Our first example demonstrates the use of timers in OCaml. Timers allow us to execute code at some point in the future or repeatedly at some interval. We’ll look at how to create and use timers in OCaml.

open Unix

let () =
  (* Timers represent a single event in the future. We use Unix.select
     to wait for a specified amount of time. This timer will wait 2 seconds. *)
  let timer1 = Unix.gettimeofday () +. 2.0 in
  let _ = Unix.select [] [] [] 2.0 in
  Printf.printf "Timer 1 fired\n";

  (* If you just wanted to wait, you could have used Unix.sleep.
     Here's an example of a cancelable timer using threads. *)
  let timer2_fired = ref false in
  let timer2_thread = Thread.create (fun () ->
    Unix.sleep 1;
    timer2_fired := true;
    Printf.printf "Timer 2 fired\n"
  ) () in

  (* We can cancel the timer by killing the thread before it completes *)
  Thread.delay 0.5;
  Thread.kill timer2_thread;
  
  if not !timer2_fired then
    Printf.printf "Timer 2 stopped\n";

  (* Give enough time for timer2 to fire, if it was going to *)
  Unix.sleep 2

To run this program, save it as timers.ml and compile it with the following command:

$ ocamlc unix.cma threads.cma timers.ml -o timers

Then run the compiled program:

$ ./timers
Timer 1 fired
Timer 2 stopped

The first timer will fire approximately 2 seconds after we start the program, but the second should be stopped before it has a chance to fire.

In this OCaml version:

  1. We use Unix.select to create a simple timer that waits for a specified duration.
  2. For the cancelable timer, we use OCaml’s threading capabilities. We create a thread that sleeps for 1 second before setting a flag and printing a message.
  3. To cancel the timer, we kill the thread before it completes its execution.
  4. We use Unix.sleep at the end to give enough time for the second timer to fire if it wasn’t successfully canceled.

Note that OCaml’s standard library doesn’t have a built-in timer module like Go’s time.Timer. This implementation provides similar functionality using threads and Unix module functions.