ScheduledExecutorService仅运行一次
我希望在启动Web服务之后运行一个进程,然后每隔30分钟左右运行一次(目前我正在以较小的延迟对其进行测试,以查看其是否正常运行),但是我的进程从未运行过一次。我究竟做错了什么?
这是我的代码:
@WebListenerpublic 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);
    }
}
回答:
用以下run代码包装代码try catch
只是一个猜测:正在引发异常。一个ScheduledExecutorService暂停默默地如果遇到异常。
该run方法的代码应始终被try-catch包围,以处理和吸收所有抛出的Exception。
 @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。
以上是 ScheduledExecutorService仅运行一次 的全部内容, 来源链接: utcz.com/qa/418239.html

