如何在Java中删除/ postDelayed runnables? [英] How to remove/postDelayed runnables in Java?
问题描述
在一个事件发生时,我想运行一个任务/可运行但是在2秒内延迟它的执行。
Upon an event, I'd like to run a task/runnable but delay it's execution in 2 seconds.
在这2秒内,如果发生同样的事件,我想删除之前的任务并重新发布它 - 再次延迟2秒。
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.
一个示例场景是后台编译。保存文件时,我等待2秒钟,然后开始编译类和其他类,具体取决于类。我不想一直这样做 - 特别是如果有编辑器自动保存文件,比如IntelliJ IDEA。
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.
那么,如何删除/ postDelayed runnables in Java ,如Android的Handler(删除 / postDelayed )?
So, how can I remove/postDelayed runnables in Java, like Android's Handler (remove / postDelayed)?
推荐答案
你可以使用 Executors.newScheduledThreadPool
为了安排任务,
你可以按照发布的回答:
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();
以获得排队的runnables。
in order to get the queued runnables.
这篇关于如何在Java中删除/ postDelayed runnables?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!