Alex
Alex

Reputation: 315

Shutdown scheduler - Java

I have the following class, which schedules the "update" method to be executed every 5 minutes. The thing is I want "update" to be executed a fixed number of times. When I use scheduler.shutdown() the update method does not execute anymore, but the program is still running, I suppose doing nothing.

How can I stop it completely?

static Runnable update = new Runnable() {        
    @Override
    public void run() {

        if (count >= MAX_UPDATES) {
            scheduler.shutdown();
        } else {
            //Do something
            count++;
        }
    }
}

public static void main(String[] args) {

    ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
    scheduler.scheduleAtFixedRate(update, 0, 5, TimeUnit.MINUTES);
}

Upvotes: 1

Views: 3261

Answers (2)

StormeHawke
StormeHawke

Reputation: 6207

You can use System.exit(int exitCode);

Note that if you do so, the jvm will terminate immediately. Also this is the only situation where a finally{} block will NOT execute.

Upvotes: 0

Petr Mensik
Petr Mensik

Reputation: 27496

I think you could use shutdownNow method, this should Attempts to stop all actively executing tasks and halts the processing of waiting tasks according to the docs.

Upvotes: 3

Related Questions