Spring ScheduledTask – 启动/停止支持?

有没有办法启动或停止使用上下文文件或@Scheduled注释初始化的Spring Scheduled Tasks安排的任务?

我想在需要时启动任务,并在不再需要运行任务时停止它。

如果这是不可能的,那么将任何弹簧变量注入线程的替代方法是什么?

停止已注册的@Scheduled bean不是标准function,因为在org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor对它们的访问是私有的。

如果您需要管理它们运行的​​时间,您需要以编程方式注册它们( TriggerTask ):请参阅org.springframework.scheduling.annotation.SchedulingConfigurer的文档。 在org.springframework.scheduling.config.TriggerTask类型中,有一个返回org.springframework.scheduling.Trigger类型的方法。 在那里你可以管理下一个执行时间。

在程序化注册的情况下, TriggerTask可以是bean。

以下是在Spring Boot中启动/停止调度方法的示例。 您可以使用此类API:
http:localhost:8080 / start – 用于启动固定速率为5000 ms的预定方法
http:localhost:8080 / stop – 用于停止预定方法

 import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import java.time.Instant; import java.util.concurrent.ScheduledFuture; @Configuration @ComponentScan @EnableAutoConfiguration public class TaskSchedulingApplication { public static void main(String[] args) { SpringApplication.run(TaskSchedulingApplication.class, args); } @Bean TaskScheduler threadPoolTaskScheduler() { return new ThreadPoolTaskScheduler(); } } @Controller class ScheduleController { public static final long FIXED_RATE = 5000; @Autowired TaskScheduler taskScheduler; ScheduledFuture scheduledFuture; @RequestMapping("start") ResponseEntity start() { scheduledFuture = taskScheduler.scheduleAtFixedRate(printHour(), FIXED_RATE); return new ResponseEntity(HttpStatus.OK); } @RequestMapping("stop") ResponseEntity stop() { scheduledFuture.cancel(false); return new ResponseEntity(HttpStatus.OK); } private Runnable printHour() { return () -> System.out.println("Hello " + Instant.now().toEpochMilli()); } } 

@Scheduled方法查找Application状态或ServletContext保存的变量,或者查找存储在DB中的值。 如果值为TRUE,则继续执行任务; 如果为FALSE,请勿启动。 此设置将控制计划的运行。

如果您还希望能够随意触发任务,请从Controller引用任务的方法; 这样你可以随意开火。 此外,如果它的运行时间较长,请创建第二个注释@Async方法,并从Controller调用该方法,使其在自己的线程中运行。