Question

How would one go about executing a task after x seconds unless otherwise overwritten by a new scheduled task?

The scenario is that I would like to execute a task 1 second after the user has finished typing in my JTextField. For that, I would need to schedule the task, and reschedule it every time the 'document' changes.

I tried using a ScheduledExecutorService, but scheduling just adds the task to a list, rather than cancelling the previous task.

Here's where I would like it to go:

class TextChangeListener implements DocumentListener {
    private final ??? updater = new ???();

    @Override
    public void changedUpdate(DocumentEvent arg0) {}

    @Override
    public void insertUpdate(DocumentEvent arg0) {
        update();
    }

    @Override
    public void removeUpdate(DocumentEvent arg0) {
        update();
    }

    private void update() {
        // Wait for the user to finish typing first
        updater.schedule(new Runnable() {
            @Override
            public void run() {
                doSomeStuff();
            }
        }, 1, TimeUnit.SECONDS);
    }
}
Was it helpful?

Solution

I think you were on track with your ScheduledExecutorService - you just need to hold on to the Future it returns. Check out the cancel method. I'm assuming you are using the schedule method.

So basically you'd want to do something like

if (future != null) {
    future.cancel();
}
future = // do scheduling code with ScheduledExecutorService 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top