问题
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?
Here is my code:
@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:
Wrap run
code with try catch
Just a guess: An exception is being thrown. A ScheduledExecutorService
halts silently if it encounters an Exception.
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" );
}
}
Stub out run
method
Take baby steps. Begin with a run
method that does nothing but a System.out.println
.
来源:https://stackoverflow.com/questions/44032059/scheduledexecutorservice-only-runs-once