Adder
Adder

Reputation: 5868

Scheduled task doesn't stop when web server is restarted by dev-tools

I have this problem:

I am scheduling a task to run every 10 minutes. When it runs, I expect to receive two emails from two checks failing.

However, when I edit my project, the dev-tools pick up the changes and restart the spring application. But here is the problem: I still receive emails from the old application running.

What can I do to properly terminate the application? I am afraid that this problem will also affect the production environment.

Code:

@Component
public class CheckRunner implements Runnable {
    private static final Logger log = LoggerFactory.getLogger(CheckRunner.class);

    private static boolean runOnce = true;

    private final long DEFAULT_CHECKING_INITIAL = 1L;
    private final long DEFAULT_CHECKING_PERIOD = 10L;

    @Autowired
    public EmailServiceImpl emailService;

    /**
     * Construct and schedule a CheckRunner 
     */
    public CheckRunner() {
        if(runOnce) {
            runOnce = false;
            log.info("Starting check runner.");
            ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
            exec.scheduleAtFixedRate(this, DEFAULT_CHECKING_INITIAL , DEFAULT_CHECKING_PERIOD, TimeUnit.MINUTES);
        }
    }

    /**
     * Run the checks once
     */
    @Override
    public void run() {
        log.info("Checking thread running.");
        checks();
    }

    /**
     * Do the checks
     */
    private void checks() {
        StringBuilder sb = new StringBuilder();
        //sb.append("<pre>");
        WebServerAvailablityCheck.runAllChecks(sb, emailService);
        //sb.append("</pre>");
    }

}

Upvotes: 1

Views: 159

Answers (1)

Andy Brown
Andy Brown

Reputation: 12999

If you implement java.io.Closeable on your CheckRunner bean and call shutdown() on the executor from within it then Spring will call Closeable.close() when the bean is destroyed. This will cause your executor thread to close gracefully.

Upvotes: 1

Related Questions