等待x秒或直到条件变为真 [英] wait x seconds or until a condition becomes true

查看:60
本文介绍了等待x秒或直到条件变为真的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何等待x秒或直到条件变为真?等待期间应定期测试条件。目前,我正在使用此代码,但是应该有一个简短的函数。

How to wait x seconds or until a condition becomes true? The condition should be tested periodically while waiting. Currently I'm using this code, but there should be a short function.

for (int i = 10; i > 0 && !condition(); i--) {
    Thread.sleep(1000);
}


推荐答案

假设您想要的是因此,相对于重新设计代码的建议,您应该查看 Awaitility

Assuming you want what you asked for, as opposed to suggestions for redesigning your code, you should look at Awaitility.

例如,如果要查看是否在接下来的10秒内创建文件,可以执行以下操作:

For example, if you want to see if a file will be created within the next 10 seconds, you do something like:

await().atMost(10, SECONDS).until(() -> myFile.exists());

它主要用于测试,但是它有特定的请求技巧来等待任意条件,具体由没有明确的同步或休眠呼叫的呼叫者。如果您不想使用该库,则只需阅读代码即可了解其运行方式。

It's mainly aimed at testing, but does the specific requested trick of waiting for an arbitrary condition, specified by the caller, without explicit synchronisation or sleep calls. If you don't want to use the library, just read the code to see the way it does things.

在这种情况下,可以归结为类似的轮询循环到问题,但使用Java 8 lambda作为参数传递,而不是内联条件。

Which, in this case, comes down to a similar polling loop to the question, but with a Java 8 lambda passed in as an argument, instead of an inline condtion.

这篇关于等待x秒或直到条件变为真的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆