java中的等待性

Ran*_*njR 3 awaitility

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

我有一个电话如下:

System.out.println(...)
await().atMost(10,Duration.SECONDS).until(myFunction());
and some code here....
Run Code Online (Sandbox Code Playgroud)

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

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

Pet*_*esh 5

等待的默认轮询间隔是 100 毫秒(即 0.1 秒)。它记录在 wiki 的“轮询”下。

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

with().pollInterval(Duration.ONE_SECOND).await().atMost(Duration.TEN_SECONDS).until(myFunction());
Run Code Online (Sandbox Code Playgroud)

这应该每秒完成一次轮询,持续时间长达 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);
    }
}
Run Code Online (Sandbox Code Playgroud)