title: Alternative to sleep inside a thread
body: <p>Various answers suggest it is a bad idea to sleep inside a thread, for example: <a href="https://stackoverflow.com/questions/5793177/how-to-abort-a-thread-when-it-is-sleeping">Avoid sleep</a>. Why exactly?  One reason often given is that it is difficult to gracefully exit the thread (by signalling it to terminate) if it is sleeping.</p>
  
  <p>Let's say I wanted to periodically check for new files in a network folder, maybe once every 10s. This seems perfect for a thread with the priority set to low (or lowest) because I don't want the potentially time-consuming file I/O to impact my main thread.</p>
  
  <p>What are the alternatives? Code is given in Delphi but would apply equally to any multi-threaded application:</p>
  
  <pre><code>procedure TNetFilesThrd.Execute();
  begin
      try
          while (not Terminated) do
              begin
              // Check for new files
              // ...
  
              // Rest a little before spinning around again
              if (not Terminated) then
                  Sleep(TenSeconds);
              end;
      finally
          // Terminated (or exception) so free all resources...
      end;
  end;
  </code></pre>
  
  <p>A minor modification might be:</p>
  
  <pre><code>// Rest a little before spinning around again
  nSleepCounter := 0;
  while (not Terminated) and (nSleepCounter &lt; 500) do
      begin
      Sleep(TwentyMilliseconds);
      Inc(nSleepCounter);
      end;
  </code></pre>
  
  <p>but this still involves a Sleep...</p>