Timer的使用

初学者可能会遇到,程序只执行一次情况,但想实现的是循环执行。查看API,可以看到主要是在于使用schedule()方法时参数多少问题?
1、只执行一次,如下:
public void schedule(TimerTask task, long delay);//程序启动后,延迟多少ms执行run()
public void schedule(TimerTask task, Date time) ;//程序启动后,在什么时间执行一次。

2、循环执行(实际只比上面执行单次,多了一个参数period,即循环的周期。
public void schedule(TimerTask task, long delay, long period);
public void schedule(TimerTask task, Date firstTime, long period);

另外看API时会发现还有一个scheduleAtFixedRate()方法,此方法简单说就是不管上次的执行结果如何,只要是到了下一个周期实际的实际点,就立马执行这次;
而schedule()是如果上一次执行因某原因有延迟,则下一次执行时,在上一次时间的基础上加上循环周期,作为下次执行的时间点。
即:schedule()更注重执行时间的稳定性,而scheduleAtFixedRate()注重执行的效率。
详细可参考其他同学精讲的博客https://www.cnblogs.com/visec479/p/4096880.html



/**
* Schedules the specified task for repeated <i>fixed-delay execution</i>,
* beginning after the specified delay. Subsequent executions take place
* at approximately regular intervals separated by the specified period.
*
* <p>In fixed-delay execution, each execution is scheduled relative to
* the actual execution time of the previous execution. If an execution
* is delayed for any reason (such as garbage collection or other
* background activity), subsequent executions will be delayed as well.
* In the long run, the frequency of execution will generally be slightly
* lower than the reciprocal of the specified period (assuming the system
* clock underlying <tt>Object.wait(long)</tt> is accurate).
*
* <p>Fixed-delay execution is appropriate for recurring activities
* that require "smoothness." In other words, it is appropriate for
* activities where it is more important to keep the frequency accurate
* in the short run than in the long run. This includes most animation
* tasks, such as blinking a cursor at regular intervals. It also includes
* tasks wherein regular activity is performed in response to human
* input, such as automatically repeating a character as long as a key
* is held down.
*
* @param task task to be scheduled.
* @param delay delay in milliseconds before task is to be executed.
* @param period time in milliseconds between successive task executions.
* @throws IllegalArgumentException if {@code delay < 0}, or
* {@code delay + System.currentTimeMillis() < 0}, or
* {@code period <= 0}
* @throws IllegalStateException if task was already scheduled or
* cancelled, timer was cancelled, or timer thread terminated.
* @throws NullPointerException if {@code task} is null
*/
public void schedule(TimerTask task, long delay, long period) {
if (delay < 0)
throw new IllegalArgumentException("Negative delay.");
if (period <= 0)
throw new IllegalArgumentException("Non-positive period.");
sched(task, System.currentTimeMillis()+delay, -period);
}

猜你喜欢

转载自www.cnblogs.com/lao-gao/p/10810370.html