Tickers in Pascal
program Tickers;
uses
SysUtils, DateUtils;
var
ticker: TTimer;
done: Boolean;
procedure TimerEvent(Sender: TObject);
begin
WriteLn('Tick at ', DateTimeToStr(Now));
end;
begin
done := False;
// Create a timer that fires every 500 milliseconds
ticker := TTimer.Create(nil);
ticker.Interval := 500;
ticker.OnTimer := @TimerEvent;
ticker.Enabled := True;
// Run the timer for 1600 milliseconds
Sleep(1600);
// Stop the timer
ticker.Enabled := False;
ticker.Free;
WriteLn('Ticker stopped');
end.Tickers in Pascal can be implemented using the TTimer class, which is similar to the concept of tickers in other languages. Here’s an example of a ticker that ticks periodically until we stop it.
The TTimer class is used to create a timer that fires an event every 500 milliseconds. We set up an event handler TimerEvent that prints the current time when the timer fires.
In the main program:
- We create a
TTimerobject and set its interval to 500 milliseconds. - We assign our
TimerEventprocedure to theOnTimerevent of the timer. - We enable the timer by setting
EnabledtoTrue. - We let the program run for 1600 milliseconds using the
Sleepfunction. - After 1600 milliseconds, we stop the timer by setting
EnabledtoFalseand free the timer object.
When we run this program, the ticker should tick 3 times before we stop it.
$ fpc tickers.pas
$ ./tickers
Tick at 2023-06-01 15:30:00
Tick at 2023-06-01 15:30:00
Tick at 2023-06-01 15:30:01
Ticker stoppedNote that Pascal’s TTimer is not as precise as timers in some other languages, so the exact timing of the ticks may vary slightly.
Comments powered by Disqus