1

I need to perform a task every x seconds and I can accomplish that goal using the code below:

var task: ITask;
begin

  task := TTask.Create(
    procedure()

    begin

      //infinite loop
      while 1 = 1 do
      begin

        //time interval
        sleep(15000);


        //do something every x seconds

      end;

    end);

  task.Start;

However, when using sleep (x) I cannot finish the task at any time, for example, when I close the form (I'm using VCL).

What would be an alternative to perform a task infinitely at a fixed interval, but with the possibility of interrupting the task without waiting for sleep to finish? I saw an article about using TEvent, however I didn't quite understand how it works.

Marcoscdoni
  • 955
  • 2
  • 11
  • 31
  • See [How do you detect that a TEvent has been set?](https://stackoverflow.com/q/13993041/576719) Instead of calling `Sleep()`, just call the event `WaitFor(15000)` method. If the event is signalled, break the task, otherwise just do the loop work task. – LU RD Nov 01 '20 at 22:52
  • I'll try it. Thanks – Marcoscdoni Nov 01 '20 at 23:51

1 Answers1

1

Instead of Sleep, use a waitable object, such as TEvent, and signal it when you want to end the task. Wait on the object for X seconds. If signaled, exit. If timed out, do the task. Repeat in a loop

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770