Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ScheduledExecutorService only runs once

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);
    }
}
like image 352
MMAdams Avatar asked May 17 '17 18:05

MMAdams


1 Answers

See this longer Answer of mine on a similar Question.

Wrap run code with try catch

Just a guess: An exception is being thrown. A ScheduledExecutorService halts silently if it encounters an Exception, with no further scheduled work performed.

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.

like image 93
Basil Bourque Avatar answered Sep 20 '22 15:09

Basil Bourque