Gem #15: Timers

by Anh Vo —Santa Clara, California

Let's get started…

Timers are essential software elements of embedded and real-time systems. Thus, making an intuitive and easy way to create timers helps in the software design process. Ada provides a predefined package named Ada.Real_Time.Timing_Events for doing just that. With this package, a timer, one-shot or periodic one, can be created with a breeze. Furthermore, these timers can be genericized for different durations. Going one step further these generic timers can be combined in a single generic package as shown below along with the test codes. Note that the test codes are pretty crude. However, the output is printed out for each second approximately. Thus, the test results can be checked using one thousand count rule, one thousand one, one thousand two...

Here is an example for creating a 250 millisecond one-shot timer.

 
with Generic_Timers;
with Ada.Real_Time;
with Ada.Text_Io;

--...
declare
   use Ada;
   Span : constant Time_Span := Real_Time.Milliseconds (250);
   Timer_Id : constant String := "250 Millisecond One Shot timer";

   procedure Timer_Handler is
   begin
      Put_Line ("Do whatever is necessary when the timer expires");
   end Timer_Handler;

   package The_Timer is new Generic_Timers (True, Timer_Id, Span, Timer_Hander); --timer object
begin
   --...
   The_Timer.Start;
   --...
end;
--...

Other one-shot timers and periodic timers for different durations are in the test package Timers_Test. Note that at my current project creating a timer takes five to ten times longer and much less intuitive. On this note, enjoy it with a smile.

Related Source Code

Ada Gems example files are distributed by AdaCore and may be used or modified for any purpose without restrictions.

gem_15.ada