2013-05-18 93 views
0

在Java中,我使用下面的代碼的計時器:Java技術任務停止計時器

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

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

如果在以後的日子,我想停止該定時器,什麼是最好的方式代碼呢?

回答

0

t.cancel();其中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(); 
    } 
}