Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 769
DD. Avatar asked Aug 24 '11 15:08

DD.


1 Answers

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()

like image 94
Tobi Avatar answered Sep 30 '22 05:09

Tobi