Java timer (Timer TimerTask) details and example code

  • 2020-05-30 20:04:04
  • OfStack

Java timer

The two classes used to implement the timer function in JAVA are Timer and TimerTask

The Timer class is the class used to perform tasks, and it takes 1 TimerTask as an argument

Timer has two modes of executing tasks. The most commonly used mode is schedule, which can execute tasks in two ways :1: at a certain time (Data), and 2: after a certain time (int delay). Both of these modes can specify the frequency of task execution

1. Simple example

So let's write one class


public class TimeTest {
public static void main(String[] args) {
  
   Timer timer = new Timer();
   timer.schedule(new MyTask(),1000,2000);
}

And then I'll write a class


public class MyTask extends TimerTask{

  @Override
  public void run() {
 System.out.println(" Began to run ");    
  }
}

This completes a simple timer, but there is another way to write these two classes into one class, the inner class

2. The inner class


public class SerchRun {

  protected static void startRun(){
    Timer timer = new Timer();
     TimerTask task =new TimerTask(){
       public void run(){
         System.out.println(" Began to run "); // Write the method you want to call here 
       }
     };
   timer.scheduleAtFixedRate(task, new Date(),2000);// The current time starts   Each time interval 2 Seconds to restart 
   // timer.scheduleAtFixedRate(task, 1000,2000); // 1 Seconds after launch   Each time interval 2 Seconds to restart          
   }
  
  public static void main(String[] args) {
   SerchRun.startRun();
  }
}

The difference between schedule and scheduleAtFixedRate is that if you specify that the start time for execution is before the current system running time, scheduleAtFixedRate will count the past time as a cycle, while schedule will not count the past time.

Such as:


SimpleDateFormat fTime = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
 Date d1 = fTime.parse("2005/12/30 14:10:00");
 
 t.scheduleAtFixedRate(new TimerTask(){
  public void run()
  {
    System.out.println("this is task you do6");
  }
 },d1,3*60*1000);

The interval is 3 minutes, and the specified start time is 14:10:00 on December 30, 2005/12. If I execute this program at 14:17:00, it will print 3 times immediately


this is task you do6   //14:10
this is task you do6   //14:13
this is task you do6   //14:16

And notice that the next execution is at 14:19, not 14:20. That is, start timing from the specified start time, not from the execution time.

However, if the schedule method is used above, the interval time is 3 minutes, and the specified start time is 2005/12/30 14:10:00, then the program will be executed at 14:17:00, and the program will be executed once immediately. And the next execution time is 14:20, not the period from 14:10 (14:19).

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: