Can I skip the current execution delay or restart immediately an Scheduled Execution Service?

663 views Asked by At

I have an Scheduled Execution Service that executes a method every X seconds. Is it possible to have a method that can force the Scheduled Execution Service to skip the remaining time in the execution delay and call the method immediately. Or can I simply stop it and restart it immediately?

here is my code:

Runnable runnable = new Runnable() {
    public void run() {

        callTheFunction();

    }
};

ScheduledExecutorService executor;
executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(Runnable, 0, 5, TimeUnit.SECONDS); // 0 sec delay | 5 sec repeat

public void restartTheExecutor() {
    // code to restart it or skip the remaining time.
}

Here is my updated and working code, it contains a boolean in the parameters which must be set to false the first run.

public void restartExecutor(View v, boolean stopRequiered) {

    if (stopRequiered) {
        scheduled.cancel(true);
    }

    Runnable runnable = new Runnable() {
        public void run() {
            nextExpression();
        }
    };

    ScheduledExecutorService executor;
    executor = Executors.newScheduledThreadPool(1);
    scheduled = executor.scheduleAtFixedRate(runnable, 0, 3, TimeUnit.SECONDS); // 0 sec delay | 5 sec repeat

}
1

There are 1 answers

5
Zbynek Vyskovsky - kvr000 On BEST ANSWER

It's not possible to enforce the scheduled function to run immediately with ScheduledExecutorService.

However, for the second question, the answer is yes. You can remove any scheduled function at any time and run it as you wish. You'll need the reference to the function separately though:

Runnable runnable = new Runnable() {
    public void run() {
        callTheFunction();
    }
};

ScheduledExecutorService executor;
executor = Executors.newScheduledThreadPool(1);
Future<?> scheduled = executor.scheduleAtFixedRate(runnable, 0, 5, TimeUnit.SECONDS); // 0 sec delay | 5 sec repeat

// cancel and run immediately:
scheduled.cancel(true);
runnable.run();

Note, that cancel() will cancel not only the next (or current) run but also all the future runs. So you'll have to reschedule again:

// reassigned scheduled to next runs:
scheduled = executor.scheduleAtFixedRate(runnable, 5, 5, TimeUnit.SECONDS); // 5 sec delay | 5 sec repeat

Or simply do both the steps by running asynchronously with 0s delay and 5s repeat again:

scheduled.cancel(true);
scheduled = executor.scheduleAtFixedRate(runnable, 0, 5, TimeUnit.SECONDS); // 0 sec delay | 5 sec repeat