TimerTask是java.util包中定义的抽象类。TimerTask类定义了一个可以安排运行一次或重复运行一次的任务。为了定义TimerTask对象,需要实现此类,并且需要覆盖run方法。当计时器对象对其进行分解时,将隐式调用run方法。
注意: TimerTask类的实例用于定义需要定期运行的任务。
构造函数:
TimerTask():创建一个新的计时器任务
类:
public abstract class TimerTask
extends Object
implements Runnable
Java中的Java.util.TimerTask类的方法:
cancel():java.util.TimerTask.cancel()取消此计时器任务句法:
public boolean cancel()
返回:
如果此任务计划为一次性执行,则为true
尚未运行,或此任务计划重复执行。
如果任务被安排为一次,则返回false
执行并且已经运行,或者如果任务从未安排过,
或者如果任务已被取消。
run():java.util.TimerTask.run()此计时器任务要执行的操作句法:
public abstract void run()
描述:
此计时器任务要执行的操作
scheduledExecutionTime():java.util.TimerTask.scheduledExecutionTime()返回此任务最近实际执行的计划执行时间句法:
public long scheduledExecutionTime()
返回:
最近执行此任务的时间
计划以Date.getTime()返回的格式发生。
如果任务还没有,则返回值是未定义的
开始第一次执行
从类java.lang.Object继承的方法
clone
equals
finalize
getClass
hashCode
notify
notifyAll
toString
wait
Java中的Java.util.TimerTask类的示例程序
// Java program to demonstrate
// working of TimerTask class
import java.util.Timer;
import java.util.TimerTask;
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
{
public static Test obj;
public static void main(String[] args) throws InterruptedException
{
obj = new Test();
// creating an instance of timer class
Timer timer = new Timer();
// creating an instance of task to be scheduled
TimerTask task = new Helper();
// scheduling the timer instance
timer.schedule(task, 1000, 3000);
// fetching the scheduled execution time of
// the most recent actual execution of the task
System.out.println(task.scheduledExecutionTime());
synchronized(obj)
{
//this thread waits until i reaches 4
obj.wait();
}
//canceling the task assigned
System.out.println("Cancel the timer task: " + task.cancel());
// at this point timer is still running
// without any task assigned to it
// canceling the timer instance created
timer.cancel();
}
}
输出:
1495715853591
Timer ran 1
Timer ran 2
Timer ran 3
Timer ran 4
Cancel the timer task: true