scheduleAtFixedRate(TimerTask task, long delay, long period): java.util.Timer.scheduleAtFixedRate(TimerTask task, long delay, long period)在指定的延迟语法后开始,为重复的固定速率执行调度指定的任务:
public void scheduleAtFixedRate(TimerTask task, long delay, long period)
参数:
task - 要安排的任务。
delay - 执行任务前的延迟(以毫秒为单位)。
period - 连续任务执行之间的时间(以毫秒为单位)。
抛出:
IllegalArgumentException - 如果delay <0,
或者延迟+ System.currentTimeMillis()<0,或
期间<= 0
IllegalStateException - 如果任务已经存在
预定或取消,计时器被取消,
或计时器线程终止。
NullPointerException - 如果task为null
// Java program to demonstrate
// scheduleAtFixedRate method of Timer class
import java.util.Timer;
import java.util.TimerTask;
import java.util.*;
class Helper extends TimerTask
{
public static int i = 0;
public void run()
{
System.out.println("Timer ran " + ++i);
if(i == 4)
{
synchronized(Test.obj)
{
Test.obj.notify();
}
}
}
}
public class Test
{
protected static Test obj;
public static void main(String[] args) throws InterruptedException
{
obj = new Test();
//creating a new instance of timer class
Timer timer = new Timer();
TimerTask task = new Helper();
//instance of date object for fixed-rate execution
Date date = new Date();
timer.scheduleAtFixedRate(task, date, 5000);
System.out.println("Timer running");
synchronized(obj)
{
//make the main thread wait
obj.wait();
//once timer has scheduled the task 4 times,
//main thread resumes
//and terminates the timer
timer.cancel();
//purge is used to remove all cancelled
//tasks from the timer'stak queue
System.out.println(timer.purge());
}
}
}
输出:
Timer running
Timer ran 1
Timer ran 2
Timer ran 3
Timer ran 4
0