Timer in Java Thread

Viewed 95189

I have a thread which is in charge of doing some processes. I want make it so that these processing would be done every 3 seconds. I've used the code below but when the thread starts, nothing happens. I assumed that when I define a task for my timer it automatically execute the ScheduledTask within time interval but it doesn't do anything at all. What am I missing?

class temperatureUp extends Thread 
{
    @Override
    public void run()
    {
    TimerTask increaseTemperature = new TimerTask(){

        public void run() {
        try {
            //do the processing 
        } catch (InterruptedException ex) {}
        }
    };

    Timer increaserTimer = new Timer("MyTimer");
    increaserTimer.schedule(increaseTemperature, 3000);

    }
};
5 Answers

Timer & TimerTask are legacy

The Timer & TimerTask classes are now legacy. To run code at a certain time, or to run code repeatedly, use a scheduled executor service.

To quote the Timer class Javadoc:

Java 5.0 introduced the java.util.concurrent package and one of the concurrency utilities therein is the ScheduledThreadPoolExecutor which is a thread pool for repeatedly executing tasks at a given rate or delay. It is effectively a more versatile replacement for the Timer/TimerTask combination, as it allows multiple service threads, accepts various time units, and doesn't require subclassing TimerTask (just implement Runnable). Configuring ScheduledThreadPoolExecutor with one thread makes it equivalent to Timer.

Executor framework

In modern Java, we use the Executors framework rather than directly addressing the Thread class.

Define your task as a Runnable or Callable. You can use compact lambda syntax seen below. Or you can use conventional syntax to define a class implementing the Runnable (or Callable) interface.

Ask a ScheduledExecutorService object to execute your Runnable object’s code every so often.

ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor() ;

Runnable task = () -> { 
    System.out.println( "Doing my thing at: " + Instant.now() );
};

long initialDelay = 0L ; 
long period = 3L ;
TimeUnit timeUnit = TimeUnit.SECONDS ;
scheduledExecutorService.submit( task , initialDelay, period , timeUnit ) ;

…
scheduledExecutorService.shutdown() ;  // Stops any more tasks from being scheduled.
scheduledExecutorService.awaitTermination() ;  // Waits until all currently running tasks are done/failed/canceled. 

Notice that we are not directly managing any Thread objects in the code above. Managing threads is the job of the executor service.

Tips:

  • Always shutdown your executor service gracefully when no longer needed, or when your app exits. Otherwise the backing thread pool may continue indefinitely like a zombie ‍♂️.
  • Consider wrapping your task's working code in a try-catch. Any uncaught exception or error reaching the scheduled executor service results in silently halting the further scheduling of any more runs.
Related