悠悠楠杉
网站页面
正文:
在自动化测试或异步任务处理中,条件等待(如轮询检查状态)是常见需求。传统Java中往往需要重复编写while循环和try-catch块,而Groovy的闭包特性可以将其抽象为优雅的通用方法。
假设我们需要等待以下三种条件:
1. 文件是否生成完成
2. API响应是否包含预期字段
3. 数据库记录是否更新
传统写法会重复类似的循环结构:
// Java风格示例
boolean isFileReady(String path) {
while (System.currentTimeMillis() < timeout) {
if (new File(path).exists()) return true;
Thread.sleep(500);
}
throw new TimeoutException();
}
利用Groovy闭包作为"条件判断逻辑"的载体,结合Closure的延迟执行特性,我们可以提取通用等待逻辑:
// 通用等待方法
def waitForCondition(Closure<Boolean> condition, long timeoutMs = 5000) {
def start = System.currentTimeMillis()
while (System.currentTimeMillis() - start < timeoutMs) {
if (condition.call()) return true
Thread.sleep(300)
}
throw new RuntimeException("Condition not met within ${timeoutMs}ms")
}
现在只需传入不同的闭包即可实现多样化等待:
// 等待文件生成
waitForCondition { new File("/data/report.txt").exists() }
// 等待API响应字段
waitForCondition {
def response = http.get("/api/status")
response.data?.status == "completed"
}
// 带自定义超时
waitForCondition({ db.query("SELECT count FROM jobs").count > 0 }, 10000)
delegate注入上下文变量
def withRetry(Closure logic) {
logic.delegate = [maxAttempts: 3] // 闭包内可通过maxAttempts访问
logic()
}
tap方法实现配置化等待
def config = [timeout: 8000, interval: 200].tap {
waitForCondition({ /* condition */ }, it.timeout)
}