简体   繁体   English

java在任务中停止计时器

[英]java stop a timer in a task

In Java, I am using the following code for a Timer: 在Java中,我将以下代码用于Timer:

Timer timer = new Timer("WeatherUpdate");
MyTask t = new MyTask();
timer.schedule(t, 10000, 10000);

class MyTask extends TimerTask 
{
    public void run() 
    {
        PlaceWeatherObjectsInSpace();
    }
}

If at a later date, I would like to stop this timer, what is the best way to code this? 如果以后要停止此计时器,最好的编码方式是什么?

t.cancel(); where t is your TimerTask t是您的TimerTask

OR 要么

class MyTask extends TimerTask 
{

    public void run() 
    {
        if(taskHasToEnd) { //taskHasToEnd can be any boolean expression comparing current date with the 'date' at which the task should end
            cancel();
        }
        PlaceWeatherObjectsInSpace();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM