Search code examples
javarunnable

How to make a runnable terminate early


I have a runnable, the code below, whenever it's called in 10 seconds it should do whatever.

CoresManager.slowExecutor.schedule(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            if (isAtWildSafe()) {
                                player.sm("This area is now safe for you.");
                                player.setCanPvp(false);
                                player.safeWait = false;
                                removeIcon();
                            }
                        } catch (Throwable e) {
                            Logger.handle(e);
                        }
                    }
                }, 10, TimeUnit.SECONDS);

But, lets say 5 seconds has gone by, and I want to cancel the runnable before it can do its action. How would I achieve this without canceling all the active runnables.


Solution

  • The schedule(...) method should return a Future object. The Future API has a cancel(...) method.

    So to achieve what you want to do: save the Future object somewhere and then call cancel on it after 5 seconds. Note that it is OK to cancel a future that has already been run.