java 等待

Awaitility in java

我正在尝试使用 java 中的 Awaitility 包为我的集成测试编写一个场景。

我有一个电话如下:

System.out.println(...)
await().atMost(10,Duration.SECONDS).until(myFunction());
and some code here....

在这里,它等待 10 秒,直到调用 myFunction()。

我想要这样的东西,我的要求是: 它应该持续每秒调用 myFunction() 持续 10 秒。对此有更好的方法吗?

it should keep calling myFunction() for every second for a duration of 10 seconds

为什么不直接使用 Thread.sleep() 呢?

for(int i=1;10>=i;i++){
   myFunction();
   try{
      Thread.sleep(1000);
   }catch(InterruptedException e){
      System.out.println('Thread was interrupted!');
   }
}

等待的默认轮询间隔为 100 毫秒(即 0.1 秒)。它是维基中的 documented under Polling

如果要将轮询间隔设置为秒,则将其添加到等待中:

with().pollInterval(Duration.ONE_SECOND).await().atMost(Duration.TEN_SECONDS).until(myFunction());

这应该每秒完成一次轮询,最多 10 秒。

这是一个非常的简单示例:

import static org.awaitility.Awaitility.*;
import org.awaitility.Duration;
import java.util.concurrent.Callable;

public class Test {

    private Callable<Boolean> waitmeme(int timeout) {
        return new Callable<Boolean>() {
            int counter = 0;
            int limit = timeout;
            public Boolean call() throws Exception {
                System.out.println("Hello");
                counter++;
                return (counter == limit);
            }
        };
    }

    public void runit(int timeout) {
        try {
            with().pollInterval(Duration.ONE_SECOND)
                  .await()
                  .atMost(Duration.TEN_SECONDS)
                  .until(waitmeme(timeout));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String args[]) throws Exception {
        int timeout = 11;
        if (args.length >= 1)
            timeout = Integer.parseInt(args[0]);
        new Test().runit(timeout);
    }
}