-
Notifications
You must be signed in to change notification settings - Fork 405
/
PollUtils.scala
49 lines (40 loc) · 1.15 KB
/
PollUtils.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.twitter.finatra.kafka.test.utils
import com.twitter.inject.Logging
import com.twitter.conversions.DurationOps._
import com.twitter.util.Duration
object PollUtils extends Logging {
def poll[T](
func: => T,
sleepDuration: Duration = 100.millis,
timeout: Duration = 60.seconds,
@deprecated("Use timeout", since = "2020-03-02") maxTries: Int = -1,
pollMessage: String = "",
exhaustedTimeoutMessage: => String = "",
exhaustedTriesMessage: (T => String) = (_: T) => ""
)(
until: T => Boolean
): T = {
var tries = 0
var funcResult: T = func
val timeoutToUse = if (maxTries == -1) {
timeout
} else {
sleepDuration * maxTries
}
val endTime = System.currentTimeMillis + timeoutToUse.inMillis
while (!until(funcResult)) {
tries += 1
if (System.currentTimeMillis() > endTime) {
throw new Exception(
s"Poll exceeded totalDuration $timeoutToUse: ${exhaustedTriesMessage(funcResult)}"
)
}
if (pollMessage.nonEmpty) {
info(pollMessage)
}
Thread.sleep(sleepDuration.inMillis)
funcResult = func
}
funcResult
}
}