我有这个类:
@Slf4j
@Component
public class MyScheduler {
@Value("${scheduler.count}")
private int SCHEDULER_COUNT;//for example 5
private final SendRequestForResponseService sendRequestForResponseService;
public MyScheduler(SendRequestForResponseService sendRequestForResponseService) {
this.sendRequestForResponseService = sendRequestForResponseService;
}
@PostConstruct
public void getRequestResponse() {
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(SCHEDULER_COUNT, new ThreadPoolTaskScheduler());
for (int i = 0; i < SCHEDULER_COUNT; i++) {
scheduledExecutorService.scheduleWithFixedDelay(sendRequestForResponseService::sendGetResponseRequest, 1, 1, TimeUnit.NANOSECONDS);
}
}
}
服务器启动后,我使用属性(SCHEDULER_COUNT(中的值创建ScheduledExecutorService
corePoolSize
并启动SCHEDULER_COUNT次。现在我有 5 个调度程序,每 1 纳秒触发一次。
现在我需要 mechanizm 来更改属性SCHEDULER_COUNT
并使用新的 cont(例如 10(重新运行ScheduledExecutorService
,而不是重新启动服务器。 有什么想法吗?
其中一个想法是编写一个 rest 服务,该服务将从值重新加载并重新启动调度程序。 但这是理论上的
我想你需要保留你的调度程序,这样你才能取消之前的任务:
@Slf4j
@Component
public class MyScheduler {
private ScheduledExecutorService scheduledExecutorService;
@Value("${scheduler.count}")
private int SCHEDULER_COUNT;//for example 5
private final SendRequestForResponseService sendRequestForResponseService;
public MyScheduler(SendRequestForResponseService sendRequestForResponseService) {
this.sendRequestForResponseService = sendRequestForResponseService;
}
@PostConstruct
public void getRequestResponse() {
setCount(env.getProperty("", Integer.class, 5);
}
public void setCount(int newCount) {
if (scheduledExecutorService != null) {
scheduledExecutorService.shutdown();
}
scheduledExecutorService = Executors.newScheduledThreadPool(SCHEDULER_COUNT, new ThreadPoolTaskScheduler());
int schedulerCount = newCount;
for (int i = 0; i < schedulerCount; i++) {
scheduledExecutorService.scheduleWithFixedDelay
(sendRequestForResponseService::sendGetResponseRequest, 1, 1,
TimeUnit.NANOSECONDS);
}
}
}
然后可以使用 REST 服务完成对setCount
的调用,是的。