java定时任务之Timer和ScheduledExecutorService

java定时任务

timer

1、执行多个任务的时候,必须第一个执行完后才会执行第二个。

2、timer是单线程执行,因此一个任务抛异常,其它任务也不能执行了。

 import java.util.Timer;  
 import java.util.TimerTask;  
   
 public class TimerTest  
 {  
     private static long start;  
   
     public static void main(String[] args) throws Exception  
     {  
   
         TimerTask task1 = new TimerTask()  
         {  
             @Override  
             public void run()  
             {  
   
                 System.out.println("task1 invoked ! "  
                         + (System.currentTimeMillis() - start));  
                 try  
                 {  
                     Thread.sleep(3000);  
                 } catch (InterruptedException e)  
                 {  
                     e.printStackTrace();  
                 }  
   
             }  
         };  
         TimerTask task2 = new TimerTask()  
         {  
             @Override  
             public void run()  
             {  
                 System.out.println("task2 invoked ! "  
                         + (System.currentTimeMillis() - start));  
             }  
         };  
         Timer timer = new Timer();  
         start = System.currentTimeMillis();  
         timer.schedule(task1, 1000);  
         timer.schedule(task2, 3000);  
   
     }  
 }  

执行结果:

task1 invoked ! 1000

task2 invoked ! 4000

newScheduledThreadPool:

1、可以多个线程同时执行不同的任务。

2、因为是多个线程所有,任务抛出异常,不影响其它任务的执行。

  • scheduleAtFixedRate : 0s后开始执行任务,前一次任务的开始时间和下次任务的开始时间中间间隔是5s , 如果前一次任务执行时间大于5s ,那么下次任务会在队列种等待,直到前一次任务执行完后,再执行。
  • scheduleWithFixedDelay : 0s后开始执行任务,前一次任务的结束时间和后一次任务的开始时间中间间隔是5s。
public class Scheduled {
    static ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);
    static class Task implements Runnable {
        public void run() {
            try {
                Thread.sleep(2000L);
                System.out.println(Thread.currentThread().getName());
            } catch (Exception e) {

            }
        }
    }
    /**
     * command:执行线程
     * initialDelay:初始化延时
     * period:两次开始执行最小间隔时间
     * delay:前一次执行结束到下一次执行开始的间隔时间(间隔执行延迟时间)
     * unit:计时单位
     */
    public static void main(String[] args) {
        scheduledExecutorService.scheduleAtFixedRate(new Task(), 0L, 5000L, TimeUnit.MILLISECONDS);
        scheduledExecutorService.scheduleWithFixedDelay(new Task(), 0L, 5000L, TimeUnit.MILLISECONDS);
    }
}
posted @ 2018-03-31 11:38  姩澕  阅读(598)  评论(0编辑  收藏  举报