Timers in Pascal

Our first example demonstrates the use of timers. We often want to execute code at some point in the future, or repeatedly at some interval. Pascal’s built-in timer features make both of these tasks easy. We’ll look at timers in this example.

program Timers;

uses
  SysUtils, DateUtils;

var
  StartTime: TDateTime;

procedure Timer1Callback;
begin
  WriteLn('Timer 1 fired');
end;

procedure Timer2Callback;
begin
  WriteLn('Timer 2 fired');
end;

begin
  // Timers represent a single event in the future. You
  // tell the timer how long you want to wait, and it
  // will execute a callback function at that time.
  // This timer will wait 2 seconds.
  StartTime := Now;
  while MilliSecondsBetween(Now, StartTime) < 2000 do
    Sleep(10);
  Timer1Callback;

  // If you just wanted to wait, you could have used
  // Sleep. One reason a timer may be useful is
  // that you can cancel the timer before it fires.
  // Here's an example of that.
  StartTime := Now;
  while MilliSecondsBetween(Now, StartTime) < 1000 do
  begin
    // Simulating cancellation of the timer
    if MilliSecondsBetween(Now, StartTime) > 500 then
    begin
      WriteLn('Timer 2 stopped');
      Break;
    end;
    Sleep(10);
  end;

  // Give the timer2 enough time to fire, if it ever
  // was going to, to show it is in fact stopped.
  Sleep(2000);
end.

In this Pascal program, we simulate the behavior of timers using loops and the Sleep function. The MilliSecondsBetween function from the DateUtils unit is used to measure elapsed time.

The first timer waits for 2 seconds and then calls the Timer1Callback procedure, which prints “Timer 1 fired”.

The second timer is simulated with a loop that checks if 500 milliseconds have passed. If so, it “stops” the timer by breaking out of the loop and prints “Timer 2 stopped”. This simulates cancelling a timer before it fires.

To run the program, save it as timers.pas and compile it using a Pascal compiler. Then run the resulting executable:

$ fpc timers.pas
$ ./timers
Timer 1 fired
Timer 2 stopped

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

Note that this is a simplified simulation of timers in Pascal. For more complex timer functionality, you might need to use external libraries or platform-specific APIs.