简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM