Tickers in Ada

Our example demonstrates the use of tickers in Ada, which are similar to timers but are used for repeating actions at regular intervals. Here’s how we can implement this concept:

with Ada.Text_IO;
with Ada.Calendar;
with Ada.Real_Time;

procedure Tickers is
   use Ada.Text_IO;
   use Ada.Calendar;
   use Ada.Real_Time;

   -- Simulate a ticker channel
   protected Ticker is
      entry Wait;
      procedure Stop;
   private
      Stopped : Boolean := False;
   end Ticker;

   protected body Ticker is
      entry Wait when not Stopped is
      begin
         null;
      end Wait;

      procedure Stop is
      begin
         Stopped := True;
      end Stop;
   end Ticker;

   -- Task to simulate ticker behavior
   task Tick_Task;

   task body Tick_Task is
      Next_Time : Time := Clock;
   begin
      loop
         delay until Next_Time;
         Next_Time := Next_Time + Milliseconds(500);
         Put_Line("Tick at " & Image(Clock));
         
         select
            Ticker.Wait;
         or
            delay 0.0;
            exit;
         end select;
      end loop;
   end Tick_Task;

begin
   delay 1.6;  -- Sleep for 1600ms
   Ticker.Stop;
   Put_Line("Ticker stopped");
end Tickers;

In this Ada program, we simulate the behavior of tickers:

  1. We define a protected object Ticker to simulate a ticker channel. It has a Wait entry that blocks until the ticker is stopped, and a Stop procedure to stop the ticker.

  2. We create a task Tick_Task that simulates the periodic ticking. It uses Ada’s delay until statement to wait for precise intervals.

  3. In the main procedure, we let the ticker run for 1.6 seconds (1600ms) before stopping it.

When we run this program, the ticker should tick approximately 3 times before we stop it. The output might look something like this:

Tick at 2023-06-01 15:30:00.500
Tick at 2023-06-01 15:30:01.000
Tick at 2023-06-01 15:30:01.500
Ticker stopped

Note that Ada’s timing mechanisms are generally more precise than those in many other languages, so the ticks should occur very close to the specified intervals.

This example demonstrates how to implement periodic actions in Ada, which can be useful for various applications such as updating displays, checking for events, or performing regular maintenance tasks in a program.