TimerTask是java中定义的抽象类。util包。TimerTask类定义了一个任务,该任务可以计划为只运行一次或重复运行多次。为了定义TimerTask对象,需要实现这个类,并且需要重写run方法。当计时器对象对run方法进行推断时,会隐式调用run方法。
null
注: TimerTask类的实例用于定义需要定期运行的任务。
施工人员:
- TimerTask() :创建新的计时器任务
宣言:
public abstract class TimerTask extends Object implements Runnable
方法:
- cancel():java。util。TimerTask。取消 取消此计时器任务
语法:
public boolean cancel() Returns: true if this task is scheduled for one-time execution and has not yet run, or this task is scheduled for repeated execution. Returns false if the task was scheduled for one-time execution and has already run, or if the task was never scheduled, or if the task was already cancelled.
- run():java。util。TimerTask。跑() 此计时器任务要执行的操作
语法:
public abstract void run() Description: The action to be performed by this timer task
- scheduledExecutionTime():java。util。TimerTask。scheduledExecutionTime() 返回此任务最近实际执行的计划执行时间
语法:
public long scheduledExecutionTime() Returns: the time at which the most recent execution of this task was scheduled to occur, in the format returned by Date.getTime(). The return value is undefined if the task has yet to commence its first execution
从java类继承的方法。lang.反对
- 克隆
- 等于
- 定稿
- getClass
- 哈希码
- 通知
- 通知所有人
- 托斯特林
- 等待
演示TimerTask类用法的Java程序
// 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
参考:
本文由 马扬克·库马尔 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END