我正在运行一个Spring Boot应用程序,并尝试使用@Scheduled
注释以特定延迟运行两个作业。
我想在特定条件下以编程方式取消这些作业。建议的方法是什么?以下是我的应用程序的配置:
Main.java
@SpringBootApplication
@EnableScheduling
public class Main implements CommandLineRunner {
static LocalDateTime startTime = LocalDateTime.now();
public static void main(String[] args) {
SpringApplication app = new SpringApplication(Main.class);
app.setBannerMode(Banner.Mode.OFF);
app.run(args);
}
@Override
public void run(String... args) throws Exception {
}
}
Job1.java
@Component
public class Job1 {
@Scheduled(fixedDelay = 10000)
public void run() {
System.out.println("Job 1 running");
}
}
Job2.java
@Component
public class Job1 {
@Scheduled(fixedDelay = 10000)
public void run() {
System.out.println("Job 2 running");
}
}
答案 0 :(得分:2)
您需要通过Spring TaskScheduler
界面的其中一个实施计划任务,例如TimerManagerTaskScheduler或ThreadPoolTaskScheduler,获取ScheduledFuture个对象。
public interface TaskScheduler {
ScheduledFuture schedule(Runnable task, Trigger trigger);
ScheduledFuture schedule(Runnable task, Date startTime);
ScheduledFuture scheduleAtFixedRate(Runnable task, Date startTime, long period);
ScheduledFuture scheduleAtFixedRate(Runnable task, long period);
ScheduledFuture scheduleWithFixedDelay(Runnable task, Date startTime, long delay);
ScheduledFuture scheduleWithFixedDelay(Runnable task, long delay);
}
ScheduledFuture
object提供取消任务的方法(ScheduledFuture.cancel())
答案 1 :(得分:0)
计划方法有预定的未来。在您的方法中获取此未来的句柄,然后您可以调用取消来取消该作业 您可以参考Spring-Boot stop Scheduled Task started using @Scheduled annotation和stop Spring Scheduled execution if it hangs after some fixed time