在java中调用一组方法之间引入延迟
我有一个特定的用例,我有10个方法需要测试,连续调用它们大约5分钟。为了避免加载后端处理这些调用,我计划在每个方法调用之间有一秒的延迟 我的代码如下所示:在java中调用一组方法之间引入延迟,java,Java,我有一个特定的用例,我有10个方法需要测试,连续调用它们大约5分钟。为了避免加载后端处理这些调用,我计划在每个方法调用之间有一秒的延迟 我的代码如下所示: public static void main(String[] args) { for (int i = 1; i <= 10; i++) // start i at 1 for initial delay { Timer timer = new Timer(); timer.sched
public static void main(String[] args)
{
for (int i = 1; i <= 10; i++) // start i at 1 for initial delay
{
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run()
{
callMethodA();
Thread.sleep(1000);
callMethodB();
Thread.sleep(1000);
callMethodC();
Thread.sleep(1000);
callMethodD();
Thread.sleep(1000);
callMethodE();
Thread.sleep(1000);
callMethodF();
}
}, 30000 * i); // 5 second intervals
}
}
publicstaticvoidmain(字符串[]args)
{
for(int i=1;i取决于您所寻找的精度
实际上,睡眠是很好的。它实际上是让线程睡眠一段时间,而这个过程同时在做其他事情
一般来说,一种更稳健的任务调度方法是PosieDeXECutoService < /C> >,因此您可能需要考虑这一点。
但是,对代码不太好的是,基本上枚举方法调用。考虑使用多个具有一定偏移量的调度器(即,在不同的时间启动它们,这样任务不会重叠,这样您就不需要在任务内休眠)。
我有一个特定的用例,我有10个方法需要测试,连续调用它们大约5分钟。为了避免加载后端处理这些调用,我计划在每次方法调用之间有一秒的延迟
为此,我认为没有必要进行调度。您可以简单地循环n次
并调用方法,其间进行一些睡眠:
Runnable[] calls = {
() -> callMethodA(),
() -> callMethodB(),
// ...
};
for (int i = 0; i < 5; i++) {
for (Runnable runnable : calls) {
runnable.run();
Thread.sleep(1000);
}
}
Runnable[]调用={
()->callMethodA(),
()->callMethodB(),
// ...
};
对于(int i=0;i<5;i++){
for(可运行:调用){
runnable.run();
睡眠(1000);
}
}
假设Quartz Scheduler也可以用于此问题。这是一个很好的示例,可以帮助您入门。我更喜欢Thread.sleep方法,因为实际上不需要发生并发。但我会将方法放入列表中,并在循环列表时在迭代之间休眠。