2014-09-13 54 views
0

我使用Spring 4,我用這爲網絡插座定期執行任務:如何管理/停止彈簧4 ConcurrentTaskScheduler

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()需要破壞schedular。這裏的問題是,即使tomcat重新啓動,以前運行的線程仍在運行。所以當tomcat正在關閉時,該線程也應該被終止。我需要知道如何在tomcat上銷燬它或者系統崩潰?

回答

0

下面的代碼片段是從@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(在這種情況下),豆,並根據您的配置調用shutdown(其實)它的方法。

+0

謝謝。我用完整的課程更新了我的問題。我不清楚聲明'@Bean(destroyMethod =「shutdown」)'。 – 2014-09-13 16:20:04