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