DD.
DD.

Reputation: 21971

Cancelling scheduled executor

I currently have a scheduled executor which sends out a message after a delay like this:

        executor.schedule(new Runnable() {
            public void run() {
                emitter.emit( message );
            }
        }, delay, TimeUnit.MILLISECONDS);

I need to have another thread which will listen for a cancel message which will send a different message and I need to stop the above message from sending. If no cancel message is received the above sends as normal. Whats the best way to do this?

Thanks.

Upvotes: 5

Views: 5283

Answers (2)

Tobi
Tobi

Reputation: 2040

This can be done by using the return value of

ScheduledFuture<?> future = executor.schedule(new Runnable() {
      public void run() {
         emitter.emit( message );
     }
    }, delay, TimeUnit.MILLISECONDS);
future.cancel(true);  //true if task should be interrupted

or by using the shutdown() method of the executor.
Take a look at shutdown() and cancel()

Upvotes: 9

mKorbel
mKorbel

Reputation: 109815

Executor#shutdown(); or Executor#shutdownNow()

Upvotes: 1

Related Questions