Java – Scheduling task with Timer class

If you want to execute some task repeat at fix interval, Time class help you to achieve it.

Timer can do scheduling with fix interval with delay and allow defining in milliseconds.

Timer TimerTask implement with run() interface of multi threading.

  • timer.schedule(new TimerTask(),1000); run one time after 1 second
  • timer.schedule(new TimerTask(),1000,1000); start after one 1 second and repeat every 1 second infinitely

The example will run statement after 10 second and run every 1 second

import java.util.Timer;
import java.util.TimerTask;

public class TimerClass {
    public static void main(String[] args) {

    Timer timer=  new Timer();

    int startingTime=10000; //millisecond 10 seconds=10000
    int delayTime=1000; // millisecond 1 second
     timer.schedule(new TimerTask()
       {
        public void run() {
         System.out.println("Timer repeat statement");
        }
      },startingTime,delayTime);

    }
}
Bookmark  

 

4 Responses to “Java – Scheduling task with Timer class”

  1. Jack Robinson says:

    Thank u for this code. it is very useful for java starter like me.

    Anyways if u inform that whether there is any possibility of stop timer before execution of another function and then again restart that.

  2. anil kumar nayak says:

    dude, simply a great example.but how to stop this timer?? i had to close the eclipse to stop running of this program..pls let me know,how to stop

  3. cekenit_chan says:

    thanx for d code…but it cause me panicked b\’coz d timer wont stop…i dun have any idea how to stop it so i need to close my NetBeans…=,(

  4. Avinash says:

    thanks for the code … it worked for me very well

Leave a Reply

Security Code:

 

  Random Post