Detail the java timing task

  • 2020-05-07 19:39:42
  • OfStack

If   needs to perform some simple timing tasks in our programming process, we can consider using Timer timing tasks in JDK. The following LZ analyzes the java Timer timer in terms of its principle, examples, and Timer defects.

1. Introduction
          a complete timing task in java needs to be completed by Timer and TimerTask classes. They are defined in API as Timer: 1, a tool that threads use to arrange later tasks to be performed in background threads. You can schedule tasks to be executed once or repeatedly on a regular basis. A task arranged by TimerTask: Timer for 1 or repeated execution. We can understand that Timer is a timer tool used to schedule tasks in a background thread, while TimerTask is an abstract class whose subclass represents a task that can be scheduled by Timer.
Timer class
The         utility class Timer provides four constructors, each of which starts the timer thread, and the Timer class guarantees that multiple threads can share a single Timer object without external synchronization, so the Timer class is thread-safe. But because each one Timer object corresponding to a single background thread, for all the timer task order, 1 case like our thread consumed task execution time should be very short, but due to special circumstances a timer task execution time is too long, then he will be "exclusive" timer task execution threads, followed by all threads must be waiting for it to finish, it will delay the follow-up task execution, make these tasks are stacked in 1 case, specific situation analysis behind us.
          when the program initializes Timer, the timing task will be executed according to the time we set. Timer provides schedule method, which has multiple ways of overloading to adapt to different situations, as follows:
          schedule(TimerTask task, Date time) : schedules the execution of a specified task at a specified time.
          schedule(TimerTask task, Date firstTime, long period
          schedule(TimerTask task, long delay) : arrange to perform a specified task after a specified delay.
          schedule(TimerTask task, long delay, long period) : scheduling a specified task for repeated, fixed delay execution after the specified delay.
          also overloads the scheduleAtFixedRate method. The scheduleAtFixedRate method is the same as schedule, but with different emphases.
        scheduleAtFixedRate(TimerTask task, Date firstTime, long period) : schedule a specified task to be repeated at a fixed rate at a specified time.
        scheduleAtFixedRate(TimerTask task, long delay, long period) : scheduling a specified task for repeated, fixed-rate execution after a specified delay.
TimerTask
The           TimerTask class is an abstract class that is scheduled by Timer for a single or repeated task. It has an abstract method, run(), which is used to perform the action to be performed by the corresponding timer task. So each specific task class must inherit TimerTask, and then override the run() method.
          also has two non-abstract methods:
          boolean cancel() : cancels this timer task.
          long scheduledExecutionTime() : returns the last scheduled execution time for the actual execution of this task.

2 instances
2.1 specifies the delay time for scheduled tasks


public class TimerTest01 { 
  Timer timer; 
  public TimerTest01(int time){ 
    timer = new Timer(); 
    timer.schedule(new TimerTaskTest01(), time * 1000); 
  } 
   
  public static void main(String[] args) { 
    System.out.println("timer begin...."); 
    new TimerTest01(3); 
  } 
} 
 
public class TimerTaskTest01 extends TimerTask{ 
 
  public void run() { 
    System.out.println("Time's up!!!!"); 
  } 
} 

Operation results:
first print: timer begin...  
 
Print after 3 seconds: Time's up!!  

2.2. Perform the scheduled task at the specified time


public class TimerTest02 { 
  Timer timer; 
   
  public TimerTest02(){ 
    Date time = getTime(); 
    System.out.println(" Specify a time time=" + time); 
    timer = new Timer(); 
    timer.schedule(new TimerTaskTest02(), time); 
  } 
   
  public Date getTime(){ 
    Calendar calendar = Calendar.getInstance(); 
    calendar.set(Calendar.HOUR_OF_DAY, 11); 
    calendar.set(Calendar.MINUTE, 39); 
    calendar.set(Calendar.SECOND, 00); 
    Date time = calendar.getTime(); 
     
    return time; 
  } 
   
  public static void main(String[] args) { 
    new TimerTest02(); 
  } 
} 
 
public class TimerTaskTest02 extends TimerTask{ 
 
  @Override 
  public void run() { 
    System.out.println(" Specifies a time to execute a thread task ..."); 
  } 
} 

          will execute the thread task when the time reaches 11:39:00, of course, it will also execute after the time!! The execution result is:
specified time time=Tue Jun 10 11:39:00 CST 2014  
Specified time to execute thread tasks...    
2.3 the timed task is cycled at the specified interval after the specified time delay


public class TimerTest03 { 
  Timer timer; 
   
  public TimerTest03(){ 
    timer = new Timer(); 
    timer.schedule(new TimerTaskTest03(), 1000, 2000); 
  } 
   
  public static void main(String[] args) { 
    new TimerTest03(); 
  } 
} 
 
public class TimerTaskTest03 extends TimerTask{ 
 
  @Override 
  public void run() { 
    Date date = new Date(this.scheduledExecutionTime()); 
    System.out.println(" The execution time of this thread is: " + date); 
  } 
} 

Operation results:
: Tue Jun 10 21:19:47 CST 2014  
The execution time of this thread is Tue Jun 10 21:19:49 CST 2014  
The execution time of this thread is Tue Jun 10 21:19:51 CST 2014  
The execution time of this thread is Tue Jun 10 21:19:53 CST 2014  
The execution time of this thread is: Tue Jun 10 21:19:55 CST 2014  
The execution time of this thread is Tue Jun 10 21:19:57 CST 2014  
.................    
          for this thread task, if we don't stop the task, it will run.
         
2.4. Analyze schedule and scheduleAtFixedRate
      1), schedule(TimerTask task, Date time), schedule delay
          for both methods, if the specified scheduled execution time is scheduledExecutionTime < = systemCurrentTime, task will be executed immediately. scheduledExecutionTime will not change due to excessive execution of one task.
      2), schedule(TimerTask task, Date firstTime, long period), schedule(TimerTask task, long delay, long period)
          these two methods are a little different from the above two. As mentioned earlier, the timer task of Timer will be delayed due to the long execution time of the previous task. In both methods, the planned time of each task execution changes with the actual time of the previous task, which is scheduledExecutionTime(n+1)=realExecutionTime(n)+periodTime. That is, if the n task is somehow leading to this execution time process, it ends up leading to systemCurrentTime > = scheduledExecutionTime(n+1), this is the n+1 task will not be executed because of the arrival of the n +1 task, he will wait for the n task n +1 task task +2 scheduledExecutionTime +2 scheduledExecutionTime So these two methods pay more attention to the stability of the interval.
        3), scheduleAtFixedRate(TimerTask task, Date period
          also mentioned earlier that scheduleAtFixedRate has a different emphasis from schedule method, schedule method focuses on maintaining the stability of interval time, while scheduleAtFixedRate method is more focused on maintaining the stability of execution frequency. Here's why. In the schedule method, the delay of the first task causes the delay of the next scheduled task, while the scheduleAtFixedRate method does not cause systemCurrentTime if the n task takes too long to execute > = scheduledExecutionTime(n+1), then he doesn't do any waiting and he immediately executes n+1 task, so scheduleAtFixedRate method execution time is calculated differently from schedule, but scheduledExecutionTime(n)=firstExecuteTime +n*periodTime, and that calculation method is always the same. So scheduleAtFixedRate is more focused on keeping the execution frequency steady.

3. for Timer defects
3.1 defects of Timer
The         Timer timer can be timed (a given time to execute a task), delayed (5 seconds to execute a task), and executed periodically (every 1 second), but Timer has some drawbacks. First, Timer's support for scheduling is based on absolute time, not relative time, so it is very sensitive to changes in system time. Secondly, Timer thread will not catch the exception. If TimerTask throws an unchecked exception, it will cause Timer thread to terminate. Meanwhile, Timer will not resume the execution of the thread again. At the same time, TimerTask that has been scheduled will no longer be executed, and new tasks cannot be scheduled. So if TimerTask throws an unchecked exception, Timer will have unexpected behavior.
1), Timer manage time delay defects
        before Timer will only create one thread task when executing the scheduled task. If there are multiple threads, if one of them for some reason causes the thread task to execute too long, exceeding the interval time between the two tasks, some defects will occur:


public class TimerTest04 { 
  private Timer timer; 
  public long start;   
   
  public TimerTest04(){ 
    this.timer = new Timer(); 
    start = System.currentTimeMillis(); 
  } 
   
  public void timerOne(){ 
    timer.schedule(new TimerTask() { 
      public void run() { 
        System.out.println("timerOne invoked ,the time:" + (System.currentTimeMillis() - start)); 
        try { 
          Thread.sleep(4000);  // Thread to sleep 3000 
        } catch (InterruptedException e) { 
          e.printStackTrace(); 
        } 
      } 
    }, 1000); 
  } 
   
  public void timerTwo(){ 
    timer.schedule(new TimerTask() { 
      public void run() { 
        System.out.println("timerOne invoked ,the time:" + (System.currentTimeMillis() - start)); 
      } 
    }, 3000); 
  } 
   
  public static void main(String[] args) throws Exception { 
    TimerTest04 test = new TimerTest04(); 
     
    test.timerOne(); 
    test.timerTwo(); 
  } 
} 

According to our normal thinking, timerTwo should be executed after 3s, and the result should be:
timerOne invoked ,the time:1001  
timerOne invoked ,the time:3001  

However, as a result of sleep(4000), timerOne sleeps 4S, while Timer has one thread inside, so the time required for timeOne exceeds the interval time. As a result:
timerOne invoked ,the time:1000  
timerOne invoked ,the time:5000  

2), Timer throws exceptional defects
if TimerTask throws RuntimeException, Timer terminates all tasks. As follows:


public class TimerTest04 { 
  private Timer timer; 
   
  public TimerTest04(){ 
    this.timer = new Timer(); 
  } 
   
  public void timerOne(){ 
    timer.schedule(new TimerTask() { 
      public void run() { 
        throw new RuntimeException(); 
      } 
    }, 1000); 
  } 
   
  public void timerTwo(){ 
    timer.schedule(new TimerTask() { 
       
      public void run() { 
        System.out.println(" Will I be able to execute? "); 
      } 
    }, 1000); 
  } 
   
  public static void main(String[] args) { 
    TimerTest04 test = new TimerTest04(); 
    test.timerOne(); 
    test.timerTwo(); 
  } 
} 

Result: timerOne throws an exception, causing the timerTwo task to terminate.


Exception in thread "Timer-0" java.lang.RuntimeException 
  at com.chenssy.timer.TimerTest04$1.run(TimerTest04.java:25) 
  at java.util.TimerThread.mainLoop(Timer.java:555) 
  at java.util.TimerThread.run(Timer.java:505) 

For the defect of Timer, we can consider ScheduledThreadPoolExecutor instead. Timer is based on absolute time and is sensitive to system time, while ScheduledThreadPoolExecutor is based on relative time. Timer is a single thread internally, while ScheduledThreadPoolExecutor is a thread pool internally, so multiple tasks can be executed concurrently.
3.2 replace Timer with ScheduledExecutorService
1) problem solving


public class ScheduledExecutorTest { 
  private ScheduledExecutorService scheduExec; 
   
  public long start; 
   
  ScheduledExecutorTest(){ 
    this.scheduExec = Executors.newScheduledThreadPool(2);  
    this.start = System.currentTimeMillis(); 
  } 
   
  public void timerOne(){ 
    scheduExec.schedule(new Runnable() { 
      public void run() { 
        System.out.println("timerOne,the time:" + (System.currentTimeMillis() - start)); 
        try { 
          Thread.sleep(4000); 
        } catch (InterruptedException e) { 
          e.printStackTrace(); 
        } 
      } 
    },1000,TimeUnit.MILLISECONDS); 
  } 
   
  public void timerTwo(){ 
    scheduExec.schedule(new Runnable() { 
      public void run() { 
        System.out.println("timerTwo,the time:" + (System.currentTimeMillis() - start)); 
      } 
    },2000,TimeUnit.MILLISECONDS); 
  } 
   
  public static void main(String[] args) { 
    ScheduledExecutorTest test = new ScheduledExecutorTest(); 
    test.timerOne(); 
    test.timerTwo(); 
  } 
} 

Operation results:
timerOne,the time:1003  
timerTwo,the time:2005  
2), problem solving 2


public class ScheduledExecutorTest { 
  private ScheduledExecutorService scheduExec; 
   
  public long start; 
   
  ScheduledExecutorTest(){ 
    this.scheduExec = Executors.newScheduledThreadPool(2);  
    this.start = System.currentTimeMillis(); 
  } 
   
  public void timerOne(){ 
    scheduExec.schedule(new Runnable() { 
      public void run() { 
        throw new RuntimeException(); 
      } 
    },1000,TimeUnit.MILLISECONDS); 
  } 
   
  public void timerTwo(){ 
    scheduExec.scheduleAtFixedRate(new Runnable() { 
      public void run() { 
        System.out.println("timerTwo invoked ....."); 
      } 
    },2000,500,TimeUnit.MILLISECONDS); 
  } 
   
  public static void main(String[] args) { 
    ScheduledExecutorTest test = new ScheduledExecutorTest(); 
    test.timerOne(); 
    test.timerTwo(); 
  } 
} 

Operation results:


timerTwo invoked ..... 
timerTwo invoked ..... 
timerTwo invoked ..... 
timerTwo invoked ..... 
timerTwo invoked ..... 
timerTwo invoked ..... 
timerTwo invoked ..... 
timerTwo invoked ..... 
timerTwo invoked ..... 
........................ 

The above is the whole content of this article, about java timing task for you to introduce here, hope to help you learn.


Related articles: