timer执行定时任务方法

public void schedule(TimerTask task,
                     long delay)  说明:该方法会在设定的延时后执行一次任务。

public void schedule(TimerTask task,
                     Date time) 说明:该方法会在指定的时间点执行一次任务。

public void schedule(TimerTask task,
                     long delay,
                     long period) 说明:该方法会在指定的延时后执行任务,并且在设定的周期定时执行任务。

public void schedule(TimerTask task,
                     Date firstTime,
                     long period)  说明:该方法会在指定的时间点执行任务,然后从该时间点开始,在设定的周期定时执行任务。特别的,如果设定的时间点在当前时间之前,任务会被马上执行,然后开始按照设定的周期定时执行任务。

 

例子:

package demo;

import java.util.Date;  
import java.util.TimerTask;  

public class TestTimerTask extends TimerTask {
     public void run() {  
         Date executeTime = new Date(this.scheduledExecutionTime());  
         System.out.println("本次任务执行的时间是" + executeTime);  
 }  
}

 

 

 


package demo;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Timer;

public class TestTimer {
    public static void main(String[] args) throws ParseException {  
        Timer timer = new Timer();  
        TestTimerTask task = new TestTimerTask();  
//        timer.schedule(task, 5000L, 1000L);
        SimpleDateFormat sdf=new SimpleDateFormat("hh:MM");
        
        timer.schedule(task, sdf.parse("15:38"));
}
}


 

posted @ 2017-09-21 15:45  伤心的鸽子  阅读(405)  评论(0编辑  收藏  举报