我上了这个课:
@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个NANOSECONDS。
现在,我需要对属性SCHEDULER_COUNT
进行更改的机制,并使用新的cont(例如10)重新运行ScheduledExecutorService
,而不重新启动服务器。有什么想法吗?
其中一个想法是编写一个rest服务,该服务将从该值重新加载并重新启动调度程序。但这是理论上的
答案 0 :(得分:0)
我想您需要保留您的调度程序,以便您可以取消之前的任务:
@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
的调用。