Class A
{
long x;
method1()
{
x = current time in millisecs;
}
task()//want to run this after (x+30) time
}
我需要在 (x+30) 之后运行 task() 。 x 可能会有所不同。如果调用 method1,则任务计划在当前时间 30 秒后运行,但在这 30 时间段内,如果再次调用 method1,那么我想取消之前的任务调用,并希望在当前时间 30 秒后安排对任务的新调用时间。我应该如何创建这种类型的调度程序或任务?
查看了 scheduledthreadpoolexecutor API 但没有找到这种类型的调度程序。
最佳答案
你问了 2 个问题:
1。如何安排任意延迟的任务?
您可以使用 schedule 之一methods在 java.util.concurrent.ScheduledThreadPoolExecutor 上
int delay = System.currentTimeMillis + 30;
myScheduledExecutor.schedule(myTask, delay, TimeUnit.MILLISECONDS);
2。如何取消已在运行的任务?
您通过调用 cancel 取消任务在 Future 上这是从您调用的 schedule
方法返回的。
if (!future.isDone()){
future.cancel(true);
}
future = myScheduledExecutor.schedule(myTask, delay, TimeUnit.MILLISECONDS);
关于java - 如何在不同时间后执行任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12283908/