Details of the differences between schedule and scheduleAtFixedRate methods of timer in java

  • 2020-12-07 04:04:58
  • OfStack

timer's schedule and scheduleAtFixedRate methods 1 make no difference in general, only in certain situations -- the current task is not completed and the next task is handed over.

Let's take an example:

During the summer vacation, the teacher gave two students, schedule and scheduleAtFixedRate, homework.

The teacher asked the students to write 2 pages every day during the summer vacation and finish the homework in 30 days.

The two students finished their homework on time every day, until the 10th day, an accident happened, the two students went out to travel for 5 days, during which neither of them did their homework. The task was delayed.

At this point, the two students adopted different strategies:

schedule rescheduled the task. On the first day after returning from the trip, he did the task on the 11th day, and on the second day, he did the task on the 12th day. Finally, it took him 35 days to complete the task.

scheduleAtFixedRate is a punctual student. She always wants to finish the teacher's task on time. So on the first day after returning from the trip, she finished all the tasks she had done in the previous five days and on the 16th day.


package day01;

import java.text.SimpleDateFormat;
import java.util.Timer;
import java.util.TimerTask;

public class Test01 {
  public static void main(String[] args) {
    final Timer timer = new Timer();
    //timer.scheduleAtFixedRate(new TimerTask() {
    timer.schedule(new TimerTask() {// Try annotating this line and the top line separately 1 Test results 
      int count = 1;

      @Override
      public void run() {
        count++;
        if (count == 10) {
          try {
            Thread.sleep(5000);
          } catch (InterruptedException e) {
            System.out.println(" delay 5s");
            e.printStackTrace();
          }
        }
        SimpleDateFormat sf = new SimpleDateFormat(
            "yyyy MM dd hh:mm:ss");
        System.out.println(" Current time: "
            + sf.format(System.currentTimeMillis()) + " Planned time: "
            + sf.format(scheduledExecutionTime()));
      }
    }, 1000, 1000);
  }
}

Hope can help everybody!


Related articles: