有没有办法启动或停止使用上下文文件或@Scheduled注释初始化的Spring Scheduled Tasks安排的任务?
我想在需要时启动任务,并在不再需要运行任务时停止它。
如果无法做到这一点,可以选择将弹簧变量注入线程吗?
答案 0 :(得分:3)
停止注册的@Scheduled bean不是标准功能,因为org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor
中对它们的访问是私有的。
如果您需要管理他们运行的时间,您需要以编程方式注册它们(TriggerTask
):请参阅org.springframework.scheduling.annotation.SchedulingConfigurer
的文档。在类型org.springframework.scheduling.config.TriggerTask
中,有一个返回org.springframework.scheduling.Trigger
类型的方法。在那里你可以管理下一个执行时间。
TriggerTask
可能是bean。
答案 1 :(得分:2)
以下是在Spring Boot中启动/停止调度方法的示例。您可以使用此类API:
http:localhost:8080 / start - 用于启动固定费率为5000毫秒的预定方法
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<Void> start() {
scheduledFuture = taskScheduler.scheduleAtFixedRate(printHour(), FIXED_RATE);
return new ResponseEntity<Void>(HttpStatus.OK);
}
@RequestMapping("stop")
ResponseEntity<Void> stop() {
scheduledFuture.cancel(false);
return new ResponseEntity<Void>(HttpStatus.OK);
}
private Runnable printHour() {
return () -> System.out.println("Hello " + Instant.now().toEpochMilli());
}
}
答案 2 :(得分:1)
让@Scheduled
方法查找Application
状态或ServletContext
中保存的变量,或者查找存储在数据库中的值。如果值为TRUE,则继续执行任务;如果假,不要开始。此设置将控制计划的运行。
如果您还希望能够随意触发任务,请从Controller中引用任务的方法;那样你可以随意开火。此外,如果它的运行时间较长,请创建第二个带注释的方法@Async
,并从Controller中调用该方法,使其在自己的线程中运行。