How do I make my Delphi programs go to sleep?

How do I make my Delphi programs go to sleep?

How do I make my Delphi programs go to sleep?


Note:Since the following was written, Delphi 2.0 has added a Sleep command. The following code can be used in Delphi 2.0 (though you’d have to rename it), but it’s necessary only in Delphi 1.0.

One thing Delphi does not have is a sleep function, which causes a program to wait a number of seconds before proceeding to its nexttask. In the meantime, it will allow Windows background operations to process.

The Turbo Pascal equivalent to this is delay, but unfortunatelyI haven’t been able to find any documentation on it, so I don’t know ifit is still available. It should be, but to be safe, I came up with a newfunction called Sleep.

The procedure makes use of the Windows API function GetTickCount,which returns the number of milliseconds that have elapsed since Windowshas started. The WinAPI documentation states that after 49 days of continuoususe, the tick count recycles back to zero, so if your machine runs on acontinuous basis with Windows, you may consider this.

Here’sthe code:

{====================================================================================This code operates on a simple principle: While (Time B - Time A)< SleepLength then process background operations. ====================================================================================}procedure Sleep(SleepSecs : Integer);var  StartValue : LongInt;begin  {Initialize vars}  StartValue    := GetTickCount; {Get value of current milliseconds elapsed}  While ((GetTickCount - StartValue) <= (SleepSecs * 1000)) do    Application.ProcessMessages;end;

Although this code is essentially only two lines long, you canimplement forced delays in your programsto accommodate other processes running in the background.

See also  How IoT Tech Will Transform Logistics

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist