Java中的等待性

时间:2018-07-19 08:50:20

标签: awaitility

我正在尝试使用Java中的Awaitility包为我的集成测试编写一个方案。

我打了如下电话:

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

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

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

2 个答案:

答案 0 :(得分:0)

  

它应该持续每秒每秒调用myFunction(),持续10秒

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

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

答案 1 :(得分:0)

等待时间的默认轮询时间间隔是100毫秒(即0.1秒)。是Wiki中的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);
    }
}