Cron表达每日开始于上午09:30,间隔30分钟

时间:2017-04-06 09:27:15

标签: java cron

我希望我的日程安排工作每天在特定时间和特定时间间隔运行。

例如从上午9:30到下午11:30开始的30分钟间隔。

开始时间,结束时间和间隔将是可配置的 在运行时。

我尝试使用以下cron表达式: 0 30/30 09-23 1/1 *?

但这是每小时而不是每30分钟运行一次。

如果不能使用cronexpression,那么请欣赏使用java的任何方式。

注意:开始时间,结束时间和间隔必须在运行时配置

2 个答案:

答案 0 :(得分:2)

正如评论中所述,您可能需要多个表达式。假设你将间隔限制在60的因子(即1,2,3,4,5,6,10,15,20,30,60),你应该需要1到3个表达式。

示例:如果您说从9:45到23:15开始每5分钟一次,您需要以下表达式:

0   45/5      9 * * ?   //every 5 minutes from 9:45 to 9:59
0    0/5  10-22 * * ?   //every 5 minutes from 10:00 to 22:59
0 0-15/5     23 * * ?   //every 5 minutes from 23:00 to 23:15

您应该只能从您获得的数据中计算出来。这是一个让你入门的快速入侵:

public static List<String> getExpressions( int startHour, int startMinute, int endHour, int endMinute, int interval) {
  List<String> expressions = new ArrayList<>();

  //If the start minute is greater than the interval we need a separate expression for the first hour
  if( startMinute >= interval ) {     
    expressions.add( String.format( "0 %d/%d %d * * ?", startMinute, interval, startHour ) );

    //the main expression needs to start as early as possible in the second hour, 
    //e.g. if you start at 9:33 and have 5 minute intervals it would need to start at 10:03  (9+1 = 10, 33%5 = 3)
    startMinute %= interval;
    startHour++;
  }

  //If the end minute is lower than the last run in the end hour we need a separate epxression for the last hour
  if( endMinute < (  startMinute + 60 - interval ) ) {     
    expressions.add( String.format( "0 %d-%d/%d %d * * ?", startMinute, endMinute, interval, endHour ) );

    //the main expression needs to run up to the second to last hour
    endHour--;
  }

  //if the main expression would still be 2+ hours in length
  if( startHour < endHour ) {        
    expressions.add( String.format( "0 %d/%d %d-%d * * ?", startMinute, interval, startHour, endHour ) );
  }
  //if the main expression is only 1 hour long don't use x-x
  else if ( startHour == endHour ) {
    expressions.add( String.format( "0 %d/%d %d * * ?", startMinute, interval, startHour ) );
  }

  return expressions;
}

答案 1 :(得分:0)

我知道这已经很晚了,但最终可能会帮助别人。您实际上并不需要多个表达式即可实现目标。

0,30 9-13 * * MON-FRI // Every 30 mins from 9:00AM to 1:30PM weekdays
30 9-13 * * MON-FRI // Every 30 mins from 9:30AM to 1:30PM weekdays