繁体   English   中英

java在任务中停止计时器

[英]java stop a timer in a task

在Java中,我将以下代码用于Timer:

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

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

如果以后要停止此计时器,最好的编码方式是什么?

t.cancel(); t是您的TimerTask

要么

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