2017-05-17 79 views
0

我想要一个进程在我启动web服务之后运行,然后每隔30分钟左右(我现在用一个较小的延迟测试它,看看它是否工作),但我的流程从未运行过一次以上。我究竟做错了什么?ScheduledExecutorService只运行一次

这里是我的代码:

@WebListener 
public class SchedulerService implements ServletContextListener{ 

    @Autowired 
    UpdateSubscriberService updateSubscriberService; 

    ScheduledExecutorService scheduledExecService; 

    public SchedulerService(){ 
     scheduledExecService = Executors.newSingleThreadScheduledExecutor(); 
    } 

    @Override 
    public void contextDestroyed(ServletContextEvent arg0) { 
     scheduledExecService.shutdown(); 
    } 

    @Override 
    public void contextInitialized(ServletContextEvent arg0) { 
     scheduledExecService.scheduleWithFixedDelay(new Runnable(){ 
      @Override 
      public void run() { 
       Date date = new Date(System.currentTimeMillis()); 
       System.out.println("Running scheduled update check " + date.toString()); 
       updateSubscriberService.checkForUpdates(); 
      } 
     }, 60, 30, TimeUnit.SECONDS); 
    } 
} 
+1

你确定run()方法返回吗? – Warrior

回答

4

run代码try catch

只是一个猜测:一个异常被抛出。如果遇到异常,A ScheduledExecutorService将自动暂停。

run方法的代码应该总是被try-catch包围以处理和吸收抛出的异常。

@Override 
public void run() { 
    try { // Let no Exception reach the ScheduledExecutorService. 
     Date date = new Date(System.currentTimeMillis()); 
     System.out.println("Running scheduled update check " + date.toString()); 
     updateSubscriberService.checkForUpdates(); 
    } catch (Exception e) { 
     System.out.println("ERROR - unexpected exception"); 
    } 
} 

存根run方法

采取小步。从run方法开始,除了System.out.println之外什么也不做。

+0

当我将它更改为打印语句时,它会执行多次,因此至少现在我知道问题不在调度代码中了! – MMAdams