简体   繁体   中英

java stop a timer in a task

In Java, I am using the following code for a 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

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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