java定时任务

来源:互联网 发布:krc编辑器 mac版 编辑:程序博客网 时间:2024/03/29 08:59

该处介绍的是 ScheduledExecutorService定时周期性执行指定任务


ScheduleExecutorService接口中有四个重要的方法,实现定时任务常用的方法是:

scheduleAtFixedRate和scheduleWithFixedDelay。

1.接口scheduleAtFixedRate原型定义及参数说明

public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,              long initialDelay,              long period,              TimeUnit unit);  
command:执行线程
initialDelay:初始化延时
period:固定时间间隔(两次开始执行最小间隔时间
unit:计时单位

2.接口scheduleWithFixedDelay原型定义及参数说明

public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,                  long initialDelay,                  long delay,                  TimeUnit unit);  
command:执行线程
initialDelay:初始化延时
period:相对时间间隔(前一次执行结束到下一次执行开始的间隔时间
unit:计时单位

两个方法的区别:主要在于时间间隔。第一个的任务执行,到达固定的时间间隔,就会开始执行新的任务,但是,有一种情况必须注意,当任务的执行时间大于规定的间隔时间时,并不会开辟新的线程执行新的任务,而是等待任务结束之后立即执行新的任务,这点格外注意。第二个的任务执行,无论任务执行多久,前一次任务必须执行结束之后,等待时间间隔之后再执行新的任务。第二种比较常用,相对比较简单。

实例:

1.按指定频率周期执行某个任务(scheduleAtFixedRate)

初始化延迟0ms开始执行,每隔100ms重新执行一次任务

/**  * 以固定周期频率执行任务  */  public static void executeFixedRate() {      ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);  //也可用Executors.newSingleThreadScheduledExecutor();    executor.scheduleAtFixedRate(    new Runnable() {@Overridepublic void run() {//线程执行任务}    },      0,      100,      TimeUnit.MILLISECONDS);  } 
间隔指的是连续两次任务执行的开始时间的间隔

2.按指定频率间隔执行某个任务(scheduleWithFixedDelay)

初始化时延时0ms开始执行,本次执行结束后延迟100ms开始下次执行。

/**  * 以固定时间间隔执行任务  */  public static void executeFixedRate() {      ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);      executor.scheduleWithFixedRate(    new Runnable() {@Overridepublic void run() {//线程执行任务}    },      0,      100,      TimeUnit.MILLISECONDS);  } 

应用场景例子:

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


/**  * 获取指定时间对应的毫秒数  * @param time "HH:mm:ss"  * @return  */  private static long getTimeMillis(String time) {      try {          DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");          DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd");          Date curDate = dateFormat.parse(dayFormat.format(new Date()) + " " + time);          return curDate.getTime();      } catch (ParseException e) {          e.printStackTrace();      }      return 0;  }  


class EchoServer implements Runnable {      @Override      public void run() {          try {              Thread.sleep(50);          } catch (InterruptedException e) {              e.printStackTrace();          }          System.out.println("This is a echo server. The current time is " +                  System.currentTimeMillis() + ".");      }  }  




1 0
原创粉丝点击