Question

I am working on a bot that does some stuff at specified changing intervals. The user of the application has the option to do the stuff whenever he pleases in the GUI. However called, the main function then calculates the remaining time until next stuff should be done and passes that to the scheduler. Also, the application should be able to run for a very long time.

public final class Bot {
    private ScheduledFuture<?> mainHandle;
    private final Runnable runMainFunction;
    private boolean lock;
    private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

    public Bot () {
        runMainFunction = new Runnable() {
            @Override
            public void run() {
                if (!lock) {
                    lock = true;
                    mainFunction();
                } else {
                    //already running
                }
            }
        };
        lock = false;
        mainHandle = scheduler.schedule(runMainFunction, 0, SECONDS);
    }

    private void mainFunction() {
        doStuff();
        mainHandle = scheduler.schedule(runMainFunction, calcNewTime(), SECONDS);
        lock = false;
    }

    public void manualCall() {
        if (!lock) {
            mainHandle = scheduler.schedule(runMainFunction, 0, SECONDS);
        }
    }

(When writing this, I was under the impression that mainHandle would only store the latest task scheduled - but this is my first time with scheduling... And I am puzzled.)

The code works, but every time the mainFunction() is called, new task is created on top of previous tasks (with usually the same delay time). This causes the application to hoard tasks with every manualCall() from user, which is unwanted—I only want to keep the "freshest" task and discard the older ones.

What would be the best solution to my problem?

I would like to keep the solution as simple as possible without using frameworks.

Was it helpful?

Solution

To answer your title: Use submit, not schedule, or any related function. In particular look at the ExecutorService interface instead of ScheduledExecutorService, as its methods won't contain anything repeated.

To answer this, which I think is your actual question:

I only want to keep the "freshest" task and discard the older ones.

Note that when you schedule a task a ScheduledFuture<?> is returned. You can cancel that when a newer task is submitted.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top