Cancelling scheduled executor

限于喜欢 提交于 2019-12-19 07:54:42

问题


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.


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/7178205/cancelling-scheduled-executor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!