好的,所以我为一个void/runnable/timertask尝试了3种不同的延迟执行程序选项,我想在5秒后运行它,但我使用的所有代码都不起作用。他们会立即运行代码。
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(clearstage(), 10, 10, SECONDS);
executor.shutdown();
我尝试的第二个代码:
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleWithFixedDelay(clearstage(), 0, 5, TimeUnit.SECONDS);
executor.shutdown();
对于那些我使用了这样的可运行任务:public Runnable clearstation(){//code}我还尝试了timertask:
reviveplayerover = clearstage();
Timer timer = new Timer();
timer.scheduleAtFixedRate(reviveplayerover, 5000);
reviveplayer(namee, name);
timer.cancel();
然后使用:public TimerTask clear阶段(){//code}
您需要确保您的“main()”方法在计划任务执行之前不会退出。
// Example with a one-shot delay
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.schedule(clearstage(), 5, TimeUnit.SECONDS);
executor.shutdown();
executor.awaitTermination(6, TimeUnit.SECONDS);
System.out.println("Done.");
// And your clearstage() must be implemented like this:
private static Runnable clearstage() {
return new Runnable() {
@Override
public void run() {
// Code goes here...
}
};
}
在您的第二个示例中,使用ChenduledExecutorService
executor.scheduleWithFixedDelay(clearstage(), 0, 5, TimeUnit.SECONDS);
第二个参数是初始延迟
。这是Javadoc
ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
long initialDelay,
long delay,
TimeUnit unit)
...
initialDelay - the time to delay first execution
您正在传入0
,因此第一个调度的Runnable
不会延迟。ExecutorService. Shutdown()
运行所有已调度的任务,然后关闭。由于您也在紧接着调用Shutdown()
,因此任务将不会被调度,也不会执行。
如果使用ChenduledExecutorService
,另一种选择是使用公共的ChenduledFuture安排具有延迟的任务
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
scheduledFuture = executor.schedule(clearstage(), 5, TimeUnit.SECONDS);
executor.shutdown();
你也可以等待你预定的未来完成。从问题中不清楚你到底在寻找什么。
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
ScheduledFuture<?> scheduledFuture = executor.schedule(clearstage(), 5, TimeUnit.SECONDS);
scheduledFuture.get(); // Wait for completion
executor.shutdown()