java定时任务

1.按指定频率间隔执行某个任务。

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Aaaaa {
  public static void main(String[] args) {
    Runnable runnable = new Runnable() {
      public void run() {
        // task to run goes here
        System.out.println("Hello !!");
       }
    };
  ScheduledExecutorService service = Executors
    .newSingleThreadScheduledExecutor();
  service.scheduleAtFixedRate(runnable, 0, 10, TimeUnit.SECONDS);
  }
}

2.周期定时执行某个任务。

  1. /** 
  2.  * 获取指定时间对应的毫秒数 
  3.  * @param time "HH:mm:ss" 
  4.  * @return 
  5.  */  
  6. private static long getTimeMillis(String time) {  
  7.     try {  
  8.         DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");  
  9.         DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd");  
  10.         Date curDate = dateFormat.parse(dayFormat.format(new Date()) + " " + time);  
  11.         return curDate.getTime();  
  12.     } catch (ParseException e) {  
  13.         e.printStackTrace();  
  14.     }  
  15.     return 0;  
  16. }  

 

  1. /** 
  2.  * 每天晚上8点执行一次 
  3.  * 每天定时安排任务进行执行 
  4.  */  
  5. public static void executeEightAtNightPerDay() {  
  6.     ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);  
  7.     long oneDay = 24 * 60 * 60 * 1000;  
  8.     long initDelay  = getTimeMillis("20:00:00") - System.currentTimeMillis();  
  9.     initDelay = initDelay > 0 ? initDelay : oneDay + initDelay;  
  10.   
  11.     executor.scheduleAtFixedRate(  
  12.             new EchoServer(),  
  13.             initDelay,  
  14.             oneDay,  
  15.             TimeUnit.MILLISECONDS);  
  16. }  

 

  1. class EchoServer implements Runnable {  
  2.     @Override  
  3.     public void run() {  
  4.         try {  
  5.             Thread.sleep(50);  
  6.         } catch (InterruptedException e) {  
  7.             e.printStackTrace();  
  8.         }  
  9.         System.out.println("This is a echo server. The current time is " +  
  10.                 System.currentTimeMillis() + ".");  
  11.     }  
  12. }  
posted @ 2017-01-11 14:20  蚂蚁总督  阅读(188)  评论(0编辑  收藏  举报