gpt4 book ai didi

java - 如何管理/停止 spring 4 ConcurrentTaskScheduler

转载 作者:行者123 更新时间:2023-11-28 23:34:31 24 4
gpt4 key购买 nike

我正在使用 Spring 4。我用它来定期为 Web 套接字执行任务:

private TaskScheduler scheduler = new ConcurrentTaskScheduler();

在我的课上:

@Configuration
@EnableWebSocketMessageBroker
@EnableScheduling
@Component
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

@Autowired
private SimpMessagingTemplate template;


private TaskScheduler scheduler = new ConcurrentTaskScheduler();
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/simplemessages").withSockJS();
}

public void configureMessageBroker(MessageBrokerRegistry config) {

config.enableSimpleBroker("/topic/", "/queue/");

config.setApplicationDestinationPrefixes("/app");
}


@PostConstruct
private void broadcastTimePeriodically() {


scheduler.scheduleAtFixedRate(new Runnable() {
public void run() {
String statStr = "Server Response" + new Date();
System.out.println("thread schedular run time :" + Hello.printTime());
try {
template.convertAndSend("/topic/simplemessagesresponse", statStr);
} catch (MessagingException e) {
System.err.println("!!!!!! websocket timer error :>" + e.toString());
}

}
}, 4000));


}

@PreDestroy
private void destroyServices() {
scheduler = null; // how to destroy ?

}

public void configureClientInboundChannel(ChannelRegistration registration) {

}

public void configureClientOutboundChannel(ChannelRegistration registration) {
registration.taskExecutor().corePoolSize(4).maxPoolSize(10);
}

public boolean configureMessageConverters(List < MessageConverter > arg0) {
// TODO Auto-generated method stub
return true;
}
@Override
public void configureWebSocketTransport(WebSocketTransportRegistration arg0) {

}
}

我想知道的事情:

  1. 我发现调度程序在 4000 毫秒内运行了两次。它是怎么发生的,我该如何阻止它?

  2. 我在 tomcat 中运行这个应用程序。如您所见,destroyServices() 方法需要销毁调度程序。这里的问题是,即使再次重启tomcat,之前运行的线程还在运行。因此,当 tomcat 即将关闭时,该线程也应该终止。我需要知道如何在 tomcat 发生故障或任何系统崩溃时销毁它?

最佳答案

以下代码片段来自@EnableScheduling的文档:

   @Configuration
@EnableScheduling
public class AppConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(taskExecutor());
}

@Bean(destroyMethod="shutdown")
public Executor taskExecutor() {
return Executors.newScheduledThreadPool(100);
}
}

我认为您应该获取名为 taskExecutor 的 bean(在本例中)并调用它的 shutdown(实际上取决于您的配置)方法。

关于java - 如何管理/停止 spring 4 ConcurrentTaskScheduler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25823337/

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