Detailed explanation of schedule of method parameters of Timer in Java

  • 2021-07-03 00:10:33
  • OfStack


timer.schedule(new MyTask(),long time1,long timer2);

Today, I thoroughly understood this method that once gave me a headache. Now I will focus on 1:

The first parameter, the TimerTask class, is in the package: import Java. util. TimerTask. The consumer inherits this class and implements the public void run () method because the TimerTask class implements the Runnable interface. The second parameter means that when you call the method, the method will inevitably call the run () method in the TimerTask class TimerTask class. This parameter is the difference between the two. In Chinese, it means that after the user calls the schedule () method, he has to wait so long before he can execute the run () method for the first time. The third parameter means how often the run () method is called from the second time after the first call.

Attachment:

When technicians realize the integration of internal office system and external website 1, the most important step is to read the data from OA system and generate the final static page according to the website template. Here, a timed task is needed, and it is executed cyclically.

When technicians write timed tasks, they take it for granted that Timer.schedule(TimerTask task, longdelay) Is to execute task repeatedly. After running the program, I found that it only ran once. I always felt that there was something wrong with the code in task, and it took a long time to debug the code without results.

Carefully study java api , found:

   schedule(TimerTask task, long delay) Schedules thespecified task for execution after the specifieddelay. task is executed after a millisecond delay of delay. There is no mention of repeated execution

   schedule(TimerTask task, long delay, long period) Notes: Schedulesthe specified task for repeated fixed-delay execution, beginningafter the specified delay. task is repeated after a delay of delay milliseconds for a period of period milliseconds.

So the problem is clear schedule(TimerTask task, longdelay) Execute only once, schedule(TimerTask task, long delay, longperiod) Is the repeated execution. The key problem is that programmers mistakenly think that schedule is repeated execution, but do not carefully study API. One aspect is also insufficient English ability, and they cannot quickly understand the meaning in the process of browsing API.

Summarize


Related articles: