gpt4 book ai didi

java - Spring ScheduledTask - 启动/停止支持?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:26:16 24 4
gpt4 key购买 nike

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

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

如果这是不可能的,除了将 spring 变量注入(inject)线程之外还有什么替代方法?

最佳答案

下面是在 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());
}

}

关于java - Spring ScheduledTask - 启动/停止支持?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7107420/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com