我希望我的计划作业每天在特定时间和特定时间间隔运行。
例如,从上午 09.30 到晚上 11.30 的间隔为 30 分钟。
开始时间、结束时间和间隔可在运行时配置。
我尝试使用以下 cron 表达式:0 30/30 09-23 1/1 *?
但每小时运行一次,而不是每 30 分钟运行一次。
如果 cronexpress 无法实现,那么请使用 java 来实现它。
注意:开始时间、结束时间和间隔必须在运行时配置
我知道这已经很晚了,但最终可能会帮助别人。您实际上并不需要多个表达式来实现您的目标。
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
正如评论中已经指出的,您可能需要多个表达式。假设您将间隔限制为 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
Run Code Online (Sandbox Code Playgroud)
您应该能够仅根据您获得的数据来计算出该值。这是一个帮助您入门的快速技巧:
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14362 次 |
| 最近记录: |