解析Cron表达式

1.引入

      有些时候我们不但需要定时执行任务,而且需要获得下一次执行的时间。

      但是我们执行时间配置的是cron表达式,不能够根据上次执行的时间+执行间隔这种方式来获得。所以我们必须要解析cron

2.方法

  1.  
    Date curTime = new Date();
  2.  
    System.out.println(curTime);
  3.  
     
  4.  
    CronExpression expression;
  5.  
    try
  6.  
    {
  7.  
    expression = new CronExpression("0 30 15 * * ?");
  8.  
    Date newDate = expression.getNextValidTimeAfter(curTime);
  9.  
    System.out.println(newDate);
  10.  
    } catch (ParseException e) {
  11.  
    logger.error( "fail to parse cron express", e);
  12.  
    } catch (Exception e) {
  13.  
    logger.error( "fail to update rule nextTime", e);
  14.  
    }

          结果为:

Wed Jun 24 19:11:52 CST 2015
Thu Jun 25 15:30:00 CST 2015

       说明:

       (1)当然需要引入Quartz的依赖

  1.  
    <dependency>
  2.  
    <groupId>org.opensymphony.quartz</groupId>
  3.  
    <artifactId>quartz-all</artifactId>
  4.  
    <version>1.6.1</version>
  5.  
    </dependency>

       (2)getNextValidTimeAfter(Date date)是根据cron表达式,来获得传入时间之后的第一个执行时间

                 如上例中:当前时间为6月24日19:11:52,cron表示每天的15:30:00来执行,那么返回的结果就是6月25日15:30:00

 

猜你喜欢

转载自www.cnblogs.com/vwvwvwgwgvervae/p/12813790.html
今日推荐