Heartbeat in Java: timerTask or thread.sleep()?

Viewed 6014

I want to implement a very simple client to server heartbeat in java. The most simple approach seems to be through sleep. Consider the metacode below.

class MyClass

    Thread heartbeatThread = new Thread();

    public void() startHeartBeat{
         Thread.sleep(4000);
         sock.write("H");
      }

Is this an adequate solution, or are there pitfalls I'm not considering?

I've also considered using the java.util.Timer.scheduleAtFixedRate approach. Would this be more robust/reliable? If so, why? Here's an example (it's not as clean IMO):

class HeartBeat
{
    Timer timer=new Timer();

    public void scheduleHeartBeat(int delay, int period) {
       timer.scheduleAtFixedRate( new HeartBeatTask(), delay, period);     
       }
}   

class HeartBeatTaskextends TimerTask {
     public void run() {
     sock.write("H");     
}

Will the second approach be granted higher priority?

3 Answers
Related