python定时器中⽌_定时器Timer如何终⽌运⾏的问题
JAVA⾃带了⼀个定时器,那就是Timer,要实现⼀个Timer的demo⾮常简单:
importjava.util.Timer;importjava.util.TimerTask;class Task extendsTimerTask{
@Overridepublic voidrun() {
System.out.println("******程序执⾏******");
}
}public classTaskTest {public static voidmain(String[] args){
Timer timer= newTimer();
翁虹的老公是谁Task task= newTask() ;
timer.schedule(task,3000); //这⾥的单位是毫秒
}
}
⽤Eclipse运⾏⼀下, 问题来了,明明程序已经执⾏结束,为何却没有⾃动关闭呢?
本着学习的精神,百度了⼀下,发现问这个问题的还真不少。明明已经结束,却为什么没有⾃动终⽌程序,这是因为系统默认当Timer运⾏结束后,如果没有⼿动终⽌,那么则只有当系统的垃圾收集被调⽤的时候才会对其进⾏回收终⽌。既然这样,我们可以使⽤()来实现程序的⼿动终⽌:
importjava.util.Timer;importjava.util.TimerTask;class Task extendsTimerTask{
@Overridepublic voidrun() {
System.out.println("******程序执⾏******");
<();
}
}public classTaskTest {public static voidmain(String[] args){
Timer timer= newTimer();
Task task= newTask() ;
timer.schedule(task,3000); //这⾥的单位是毫秒
}
}
运⾏⼀下,OK,程序运⾏结束的同时,也成功终⽌。
但是()在⼀个项⽬中是不能随便调⽤的,我们做做⼩测试如此做⽆可厚⾮,但是在项⽬中如此写,太不合实际了。pubg国际服ios
表示读书刻苦的成语那么我们可以考虑⽤Timer类⾃带的cancel()⽅法,实现Timer的终⽌。
来看⼀下API中对cancel()⽅法的描述:
public voidcancel()
Terminatesthis timer(终结这个timer), discarding any currently scheduled tasks(抛弃所有当前正在执⾏的TimerTask). Does not interfere with a currently executing task (ifit exists). Once a timer has been
terminated, its execution thread terminates gracefully, and no more tasks may be scheduled on it.
Note that callingthis method from within the run method of a timer task that was invoked by this timer absolutely guarantees that the ongoing task execution is the last task execution that will ever be performed by thistimer.
This method may be called repeatedly; the second and subsequent calls have no effect.
动态清零是什么意思那么我们来实现⼀下:
importjava.util.Timer;importjava.util.TimerTask;public classTaskTest {public static voidmain(String[] args) {
粤fTimer timer= newTimer();//三秒后开始执⾏,每隔⼀秒执⾏⼀次
timer.schedule(new Task(timer), 3 * 1000, 1000);
}
}class Task extendsTimerTask {privateTimer timer;publicTask(Timer timer) {this.timer =timer;
索尼4k电视}int i = 1;
@Overridepublic voidrun() {
System.out.println("******程序执⾏******");//当执⾏到第5秒,程序结束
if (i++ == 5) {this.timer.cancel();
System.out.println("#### 程序结束 ####");
}
}
}
OK,成功结束程序。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论