1

Upon an event, I'd like to run a task/runnable but delay it's execution in 2 seconds.

During these 2 seconds, if the same event occurs, I'd like to remove the previous task and re-post it to run - again delayed by 2 seconds.

An example scenario would be background compilation. When a file is saved, I'm waiting 2 seconds and start compiling the class and other, depending classes. I don't want to do it all the time - especially if there are editors that save files automatically, like IntelliJ IDEA.

So, how can I remove/postDelayed runnables in Java, like Android's Handler (remove / postDelayed)?

AlikElzin-kilaka
  • 34,335
  • 35
  • 194
  • 277

3 Answers3

1

you can use the Executors.newScheduledThreadPool in order to schedule the task, and you can follow this post's answer :

BlockingQueue<Runnable> queue = threadPool.getQueue();

in order to get the queued runnables.

Community
  • 1
  • 1
planben
  • 680
  • 6
  • 20
  • 1
    Eventually, I used a variant of this solution, using `ScheduledThreadPoolExecutor`. I schedule a task to be delayed, but the remove didn't work, because it doesn't compare correctly tasks. What I do instead is clear the queue altogether. A bit nasty but works. – AlikElzin-kilaka May 07 '15 at 17:40
  • Wouldn't Executors.newSingleThreadScheduledExecutor give you behavior more like Android's Handler? This would guarantee that Runnables posted to it would execute sequentially instead of in parallel. – Michael Krause Jan 26 '17 at 22:25
0

To delay any task and "restart" the delay, you can use Swing timer and if it is running, use its method restart.

DangeMask
  • 531
  • 4
  • 19
0

I suppose you could use the ScheduledExecutor to accomplish this, by adding a mechanism to replace queued tasks with re-queued ones. You could look into the source code of ScheduledThreadPoolExecutor to give an idea, perhaps overriding the implementation of ScheduledFuture<?> schedule( Runnable command, long delay, TimeUnit unit ) and figuring out to avoid the scheduling, only running the tasks once.

Cheers,

Anders R. Bystrup
  • 15,729
  • 10
  • 59
  • 55