问题描述
根据我的要求,我必须在一段时间后执行一些特定的代码.为此,我选择了ScheduledExecutorService.scheduleWithFixedDelay(runnable, 0, 5, TimeUnit.SECONDS)
,对我来说很好.但是根据我的另一个要求,fixedDelay
中提到的时间应该可以在运行时配置.意味着,当前的总延迟为5秒,但是如果用户愿意,可以将其更改为60秒,并且在运行时fixedDelay
将在60秒后运行.任何帮助都将是可观的.
As per my requirement, I have to execute some particular code after certain period of time. To do the same I have chose ScheduledExecutorService.scheduleWithFixedDelay(runnable, 0, 5, TimeUnit.SECONDS)
and it's working fine for me. But according to my another requirement, the time mentioned in fixedDelay
should be configurable at runtime. Means, currently total Delay is 5 seconds but latter if user want then can change the time into 60 seconds and in runtime fixedDelay
will run after 60 seconds. Any help would be appreciable.
请查看代码:
static int i = 0;
static ScheduledExecutorService executor;
static Runnable runnable;
static ScheduledFuture<?> future;
public static void main(String args[]) {
executor = Executors
.newScheduledThreadPool(1);
runnable = new Runnable() {
@Override
public void run() {
System.out.println("Inside runnable" + i++);
changeDelay();
}
};
future =
executor.scheduleWithFixedDelay(runnable, 0, 5, TimeUnit.SECONDS);
}
public static void changeDelay() {
future.cancel(false);
future = executor.scheduleWithFixedDelay(runnable, 0, 10, TimeUnit.SECONDS);
}
在这里,我使用了changeDelay方法来更改延迟时间.但这不起作用.
Here I have used changeDelay method to change the delay time. But it's not working.
推荐答案
您需要保留返回的ScheduledFuture<?>
对象的引用:
You need to keep the reference of the returned ScheduledFuture<?>
object:
ScheduledFuture<?> handle =
scheduler.scheduleWithFixedDelay(runnable, 0, 5, TimeUnit.SECONDS);
使用此参考,您可以取消当前任务并创建另一个具有新延迟的任务:
With this reference you cancel the current task and create another one with the new delay:
handle.cancel(false);
handle = scheduler.scheduleWithFixedDelay(runnable, 0, 60, TimeUnit.SECONDS);
这里是一个例子:
public class Test5 {
static int i = 0;
static ScheduledExecutorService executor;
static Runnable runnable;
static ScheduledFuture<?> future;
public static void main(String args[]) throws InterruptedException{
executor = Executors.newScheduledThreadPool(1);
runnable = new Runnable() {
@Override
public void run() {
System.out.println("Inside runnable" + i++);
}
};
future = executor.scheduleWithFixedDelay(runnable, 0, 5, TimeUnit.SECONDS);
Thread.sleep(20000l);
changeDelay();
}
public static void changeDelay() {
boolean res = future.cancel(false);
System.out.println("Previous task canceled: " + res);
future = executor.scheduleWithFixedDelay(runnable, 0, 20, TimeUnit.SECONDS);
}
}
这篇关于在ScheduledExecutorService中重新初始化修复延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!