Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Heartbeat implementation with Thread.Sleep()

in my application I have an "heartbeat" functionality that is currently implemented in a long running thread in the following way (pseudocode):

while (shouldBeRunning)
{
    Thread.Sleep(smallInterval);

    if (DateTime.UtcNow - lastHeartbeat > heartbeatInterval)
    {
        sendHeartbeat();
        lastHeartbeat = DateTime.UtcNow;
    } 
}

Now, it happens that when my application is going through some intensive CPU time (several minutes of heavy calculations in which the CPU is > 90% occupied), the heartbeats get delayed, even if smallInterval << heartbeatInterval.

To crunch some numbers: heartbeatInterval is 60 seconds, lastHeartbeat is 0.1 seconds and the reported delay can be up to 15s. So, in my understanding, that means that a Sleep(10) can last like a Sleep(15000) when the CPU is very busy.

I have already tried setting the thread priority as AboveNormal - how can I improve my design to avoid such problems?

like image 546
Andrea Avatar asked Aug 14 '26 18:08

Andrea


1 Answers

Is there any reason you can't use a Timer for this? There are three sorts you can use and I usually go for System.Timers.Timer. The following article discusses the differences though:

http://msdn.microsoft.com/en-us/magazine/cc164015.aspx

Essentially timers will allow you to set up a timer with a periodic interval and fire an event whenever that period ticks past. You can then subscribe to the event with a delegate that calls sendHeartbeat().

Timers should serve you better since they won't be affected by the CPU load in the same way as your sleeping thread. It has the advantage of being a bit neater in terms of code (the timer set up is very simple and readable) and you won't have a spare thread lying around.

like image 168
Chris Avatar answered Aug 16 '26 08:08

Chris