class MyTimerTask extends TimerTask{
private String name;
public MyTimerTask(String inputname){
this.name=inputname;
}
public void run(){
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND,6);
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("現在時間爲:"+sf.format(calendar.getTime()));
// cancel();//取消當前任務
}
}
public class TestSchedule {
public static void main(String[] args){
Timer timer = new Timer();
timer.schedule(new MyTimerTask("sth"),2000,1000);
//TimerTask.scheduledExecutionTime()返回的是最近一次計劃執行時間
timer.schedule(new MyTimerTask("gui"),1000,1000);
/*timer.schedule的四種用法:
1.schedule(task,time)
2.schedule(task,time,period)
3.schedule(task,delay,period)
4.schedule(task,delay)
*/
// timer.cancel();終止timer下所有任務
//timer.purge();返回終止的任務數目
/*有以下兩種分情況:
1.首次執行的時間早於當前的時間
2.任務所需要的執行時間超過任務執行的週期
timer.scheduleAtFixedRate();和timer.schedule是不一樣的
對第一種情況:
schedule會從當前時間開始執行
scheduleAtFixedRate會盡量趕上執行次數。
對第二種情況:
schedule會等執行完在執行
scheduleAtFixedRate會根據時間間隔執行
所以scheduleAtFixedRate要考慮到同步
* */
}
}
基於Timer和TimerTask的定時任務
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.