Spring boot 在@Scheduler中动态更改cron表达式的Spring引导
我正试图通过使用cron表达式实现调度器来运行我的应用程序。要运行我的应用程序,我有三个条件:- 第一个条件是: 我有一些时间段,比如Spring boot 在@Scheduler中动态更改cron表达式的Spring引导,spring-boot,scheduler,Spring Boot,Scheduler,我正试图通过使用cron表达式实现调度器来运行我的应用程序。要运行我的应用程序,我有三个条件:- 第一个条件是: 我有一些时间段,比如 LocalTime [] slots = {LocalTime.of(0, 0), LocalTime.of(7, 0), LocalTime.of(13, 0), LocalTime.of(19, 0)} 现在的条件是,当JVM启动时,它将首先检查当前时间和给定时隙的持续时间。以下是检查持续时间的方法:- public static Duration fin
LocalTime [] slots = {LocalTime.of(0, 0), LocalTime.of(7, 0), LocalTime.of(13, 0), LocalTime.of(19, 0)}
现在的条件是,当JVM启动时,它将首先检查当前时间和给定时隙的持续时间。以下是检查持续时间的方法:-
public static Duration findNextSlotDuration(LocalTime now, LocalTime [] slots) {
Duration duration = null;
if(slots != null)
{
if(slots.length == 1)
{
duration = Duration.between(now, slots[0]);
}else if(slots.length > 1)
{
for (int i = 0; i < slots.length-1; i++) {
if(isBetween(now, slots[i], slots[i+1]))
{
duration = Duration.between(now, slots[i+1]);
break;
}
}
}
if(duration != null && !duration.isNegative())
return duration;
else
{
Duration d1 = Duration.between(now, LocalTime.of(23, 59)).plusMinutes(1);
Duration d2 = Duration.between(LocalTime.of(0, 0), slots[0]);
return d1.plus(d2);
}
}
return Duration.ofMinutes(5);
}
private static boolean isBetween(LocalTime candidate, LocalTime start, LocalTime end) {
return !candidate.isBefore(start) && !candidate.isAfter(end); // Inclusive.
}
publicstaticdurationfindnextslotduration(LocalTime now,LocalTime[]slots){
持续时间=空;
如果(插槽!=null)
{
if(slots.length==1)
{
duration=duration.between(现在是槽[0]);
}否则如果(插槽长度>1)
{
对于(int i=0;i
例如,如果JVM在今天下午17点启动,那么它将首先检查时间段,它将在下午13点到19点之间获得时间段,根据方法findNextSlotDuration,持续时间将为2小时,因此调度程序将在下午19点2小时后启动。另一种情况是,如果JVM今天在19小时00分29秒启动,那么它将无法获得插槽,因此,持续时间将是6小时00分29秒,然后调度程序在00:00:29点启动
现在第二个条件是:
如果JVM在完成我的任务后仍在运行,那么它将在每6小时后再次运行我的任务
最后一个条件是:
它只在周一到周六运行
所以,我想知道如何在Spring boot中使用Cron或任何更好的方法实现@Scheduler。首先,如果我理解正确,我会尝试给你一些建议。我希望这对你有帮助 您可以捕获如下所示的应用程序就绪事件,也可以在任何时候执行。您还可以使用此方法触发您的方法
@Component
public class AppReadyComponent implements ApplicationListener<ApplicationReadyEvent> {
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
// some logic
}
}
这是您预定的方法
@Scheduled(cron = "#{@getCronValue}")
public void process() {
// some logic
}
@Scheduled(cron = "#{@getCronValue}")
public void process() {
// some logic
}