如果方法本身需要一定的时间(少于 x 秒)运行,我能否知道安排方法每 x 秒运行一次的最佳方法是什么?
例如:
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
class Helper extends TimerTask
{
public void run()
{
System.out.println("Start");
//for example, the program takes about 100 ms to run and the exact time may vary
try {
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("End");
}
}
public class Test
{
public static void main(String[] args)
{
Timer timer = new Timer();
TimerTask task = new Helper();
timer.schedule(task, 0, 1000);
}
}
如何保证 0 秒之后,函数第二次被调度是 1 秒(无延迟)而不是 1.1 秒?
最佳答案
要在前一个任务结束后 x 毫秒启动任务,您可以使用 ScheduledExecutorService
:
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Test
{
public static void main(String[] args)
{
ScheduledExecutorService seService = Executors.newSingleThreadScheduledExecutor();
Runnable task = new Helper(seService);
seService.execute(task);
}
}
class Helper implements Runnable
{
private final ScheduledExecutorService seService;
Helper(ScheduledExecutorService seService) {
this.seService = seService;
}
@Override
public void run()
{
System.out.println("Start");
try {
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) { e.printStackTrace(); }
seService.schedule(this, 1000, TimeUnit.MILLISECONDS); //execute again after delay
System.out.println("End");
}
}
关于java - 如果方法本身需要一些时间,我们如何仍然每 X 秒运行一次方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54965665/