How to run a task every n seconds or periodically in Java

Hey Everyone! In this article, we will learn how we can execute or perform a particular task in Java every n seconds or periodically using the Timer and TimerTask classes.
Before directly jumping into the code, let us first understand about the TimerTask class used.


TimerTask class

TimerTask is an abstract class present in the java.util.TimerTask package in Java which implements the Runnable interface. As it is an abstract class it needs to be implemented and the run method of this class needs to be overridden.
This class is used to define a task to run every n seconds or run periodically or even for a single time.
This is done by creating an instance of the TimerTask class

Timer Class

The timer class is present in the java.util.Timer package in java.
This class consists of a method which schedules a task for a specified period of time.


Java Program to schedule a task periodically or for every n seconds

package taskn;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Taskn extends TimerTask {

   
     public void run(){
        
        System.out.println("Task scheduled ...executing now");
         try {
             Thread.sleep(3000);
         } catch (InterruptedException ex) {
             System.out.println(ex);
         }
        System.out.println("Timer task Done ");
       
    }

 
    
    public static void main(String args[]) throws Exception{
        TimerTask timerTask = new Taskn(); //reference created for TimerTask class
         
        Timer timer = new Timer(true);
        timer.scheduleAtFixedRate(timerTask, 0, 10); // 1.task 2.delay 3.period
        
         
        
        Thread.sleep(6000);
       
        timer.cancel();
        
      
    }
    
}
Output:-

Task scheduled ...executing now
Timer task Done 
Task scheduled ...executing now
Timer task Done 

I hope the above article was useful to you.
Leave a comment down below for any doubts/suggestions.

Also, read:

Leave a Reply