Search code examples
javaexecutorservicescheduledexecutorservice

Java- How to stop ScheduledExecutorService properly


Assuming, in live, below code is running for every minute using ScheduledExecutorService.

This job is triggered by startBatch.sh file.

public class TestScheduledExecutorService {
    public static void main (String a[]) {
        ScheduledExecutorService service = null;
        try {
            TestObject runnableBatch = new TestObject() {
                int i = 0;
                @Override
                public void run() {
                    testMethod (++i);
                }
            };
            service = Executors.newSingleThreadScheduledExecutor();
            service.scheduleAtFixedRate(runnableBatch, 0, 20, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

How to stop properly this daemon process after live in case any problem exists?!


Solution

  • You have to look into adding a method that you can call "somehow" to tell the service to stop. For example, your "service" could be listening on some port and take commands from there.

    Yes, that is pretty broad, but so is your input question.

    Given your comment: listening for commands is only one option here. It really depends on your requirements. It doesn't need to be a port - you can use a file watcher service and simply check for files being created in a directory for example. What you need is: a channel that a user can use to communicate with your server. How that channel looks like; up to you.

    That is the point when creating a service: you have to get your requirements straight and then design the solution that meets those.