如何停止在Java.util.Timer类中安排的任务 [英] How to stop the task scheduled in Java.util.Timer class

查看:137
本文介绍了如何停止在Java.util.Timer类中安排的任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 java.util.timer 类,我正在使用其schedule方法执行某项任务,但在执行了6次之后我必须停止其任务。

I am using java.util.timer class and I am using its schedule method to perform some task, but after executing it for 6 times I have to stop its task.

我该怎么做?

推荐答案

保留参考到某个地方的计时器,并使用:

Keep a reference to the timer somewhere, and use:

timer.cancel();
timer.purge();

停止它正在做的事情。您可以使用 static int 将此代码放入您正在执行的任务中,以计算您已经到过的次数,例如

to stop whatever it's doing. You could put this code inside the task you're performing with a static int to count the number of times you've gone around, e.g.

private static int count = 0;
public static void run() {
     count++;
     if (count >= 6) {
         timer.cancel();
         timer.purge();
         return;
     }

     ... perform task here ....

}

这篇关于如何停止在Java.util.Timer类中安排的任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆