Java-递归地安排计时器任务
是否有方法仅在方法完成后运行计时器任务。该方法可能需要10秒,但计时器设置为每5秒运行一次。我希望它在10秒结束后再运行Java-递归地安排计时器任务,java,Java,是否有方法仅在方法完成后运行计时器任务。该方法可能需要10秒,但计时器设置为每5秒运行一次。我希望它在10秒结束后再运行 Timer timer = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { longRunningMethod(); timer.schedule(task, 0, 5000
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
longRunningMethod();
timer.schedule(task, 0, 5000);
}
};
timer.schedule(task, 0, 10000);
删除
计时器计划(任务,0,5000)代码>呼叫将为您提供所需的行为
你调用的timer.schedule(任务,0,10000)代码>每十秒钟安排一次重复任务。删除计时器。计划(任务,0,5000)代码>呼叫将为您提供所需的行为
你调用的timer.schedule(任务,0,10000)代码>每十秒钟安排一次重复的任务。您可以使用which,它有一种方法可以完全做到这一点
创建并执行一个周期性操作,该操作在给定的初始延迟后首先启用,然后在一次执行结束和下一次执行开始之间的给定延迟内启用
所以你可以
ExecutorService.newScheduledExecutor()
.submit(this::longRunningMethod, 0, 1000, ChronoUnit.MILLIS);
你可以使用which,它有一个方法可以做到这一点
创建并执行一个周期性操作,该操作在给定的初始延迟后首先启用,然后在一次执行结束和下一次执行开始之间的给定延迟内启用
所以你可以
ExecutorService.newScheduledExecutor()
.submit(this::longRunningMethod, 0, 1000, ChronoUnit.MILLIS);
您需要安排一次性计时器任务,并每次创建新的TimerTask实例
class MyTimerTask extends TimerTask {
private final Timer timer;
private final long nextScheduleDelay;
MyTimerTask(Timer timer, long nextScheduleDelay) {
this.timer = timer;
this.nextScheduleDelay = nextScheduleDelay;
}
@Override
public void run() {
longRunningMethod();
timer.schedule(new MyTimerTask(timer, nextScheduleDelay), nextScheduleDelay);
}
}
Timer timer = new Timer();
timer.schedule(new MyTimerTask(timer, 1000), 0);
您需要安排一次性计时器任务,并每次创建新的TimerTask实例
class MyTimerTask extends TimerTask {
private final Timer timer;
private final long nextScheduleDelay;
MyTimerTask(Timer timer, long nextScheduleDelay) {
this.timer = timer;
this.nextScheduleDelay = nextScheduleDelay;
}
@Override
public void run() {
longRunningMethod();
timer.schedule(new MyTimerTask(timer, nextScheduleDelay), nextScheduleDelay);
}
}
Timer timer = new Timer();
timer.schedule(new MyTimerTask(timer, 1000), 0);
最底层的调度
调用每10秒启动一个新任务。每个任务每5秒另外安排一个新任务。这是棋盘上的米粒。很快,您将拥有比宇宙中原子数量更多的任务(或者更可能是OutOfMemoryError:))您不应该使用最底层的计划调用每10秒启动一个新任务。每个任务每5秒另外安排一个新任务。这是棋盘上的米粒。很快,您将有比宇宙中原子更多的任务(或者更可能是OutOfMemoryError:),您不应该使用