Timers in Ada
Our example demonstrates how to use timers in Ada. Timers allow us to execute code at a specific point in the future or repeatedly at some interval. We’ll focus on single-event timers in this example.
In this Ada example, we use tasks to implement timer functionality:
We define a
Timer
task type that takes a duration in seconds as a discriminant.The
Timer
task has two entries:Start
to begin the timer andStop
to cancel it before it fires.We create two timer instances:
Timer1
set for 2 seconds andTimer2
set for 1 second.We start
Timer1
and wait for it to complete. This is similar to the blocking nature of the Go timer.We then start
Timer2
but stop it before it has a chance to fire, demonstrating how to cancel a timer.The
select
statement in the task body allows us to either accept aStop
entry call or wait until the trigger time, whichever comes first.
To run this program, save it as timer_example.adb
and compile it using an Ada compiler:
This output shows that the first timer completed as expected, while the second timer was successfully stopped before it could fire.
Ada’s tasking model provides a different approach to concurrency compared to Go’s goroutines, but it allows us to achieve similar functionality with timers and cancellation.