ScheduledExecutorService仅运行一次 [英] ScheduledExecutorService only runs once
问题描述
我希望在启动Web服务之后运行一个进程,然后每30分钟左右运行一次(我现在以较小的延迟对其进行测试,以查看其是否正常运行),但是我的进程从未运行过不止一次.我在做什么错了?
I want a process to run after I start my webservice, and then every 30 minutes or so afterwards, (I'm testing it with a smaller delay for now, just to see if it works), but my process never runs more than once. What am I doing wrong?
这是我的代码:
@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);
}
}
推荐答案
请参见与此类似的答案问题.
See this longer Answer of mine on a similar Question.
只是一个猜测:正在引发异常. ScheduledExecutorService
遇到异常时会默默停止.
Just a guess: An exception is being thrown. A ScheduledExecutorService
halts silently if it encounters an Exception.
run
方法的代码应始终被try-catch包围,以处理和吸收所有引发的异常.
The run
method’s code should always be surrounded by a try-catch to handle and absorb any thrown 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
外什么都不做.
Stub out run
method
Take baby steps. Begin with a run
method that does nothing but a System.out.println
.
这篇关于ScheduledExecutorService仅运行一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!