Timers in Lisp
Our first example demonstrates the use of timers in Lisp. Timers allow us to execute code at a specific point in the future or repeatedly at some interval. Let’s look at how to use timers.
In this Lisp example:
We use the
sb-ext:make-timer
function to create timers. This is specific to SBCL (Steel Bank Common Lisp), one of the popular Common Lisp implementations.The first timer is scheduled to fire after 2 seconds. We use
sleep
to wait for it to fire.For the second timer, we schedule it and then immediately try to unschedule (cancel) it using
sb-ext:unschedule-timer
.We use
sleep
again at the end to give the second timer time to fire (if it was going to), demonstrating that it has indeed been cancelled.
To run this program:
The output shows that the first timer fired after approximately 2 seconds, while the second timer was successfully stopped before it had a chance to fire.
Note that the exact timing might not be precise due to system scheduling and other factors. In a real-world application, you might want to use more sophisticated synchronization mechanisms depending on your specific requirements.