Skip to content

Commit e158d9d

Browse files
committed
Fix timer not canceling
It seems to operate in its own little world and I have no idea how to make it stop when the job running it has stopped.
1 parent 4ac6d58 commit e158d9d

File tree

1 file changed

+7
-15
lines changed
  • src/main/kotlin/com/coder/gateway/sdk

1 file changed

+7
-15
lines changed

src/main/kotlin/com/coder/gateway/sdk/Retry.kt

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,9 @@ import com.intellij.openapi.diagnostic.Logger
44
import com.intellij.openapi.progress.ProcessCanceledException
55
import com.intellij.ssh.SshException
66
import kotlinx.coroutines.delay
7-
import kotlinx.datetime.Clock
87
import java.util.Random
98
import java.util.concurrent.TimeUnit
10-
import kotlin.concurrent.timer
119
import kotlin.coroutines.cancellation.CancellationException
12-
import kotlin.math.max
1310
import kotlin.math.min
1411

1512
fun unwrap(ex: Exception): Throwable? {
@@ -66,19 +63,14 @@ suspend fun <T> suspendingRetryWithExponentialBackOff(
6663
update(attempt, unwrappedEx, null)
6764
return null
6865
}
69-
val end = Clock.System.now().toEpochMilliseconds() + delayMs
70-
val timer = timer(period = TimeUnit.SECONDS.toMillis(1)) {
71-
val now = Clock.System.now().toEpochMilliseconds()
72-
val next = max(end - now, 0)
73-
if (next > 0) {
74-
update(attempt, unwrappedEx, next)
75-
} else {
76-
cancel()
77-
}
78-
}
7966
logger.error("Failed to $label (attempt $attempt; will retry in $delayMs ms)", originalEx)
80-
delay(delayMs)
81-
timer.cancel()
67+
var remainingMs = delayMs
68+
while (remainingMs > 0) {
69+
update(attempt, unwrappedEx, remainingMs)
70+
val next = min(remainingMs, TimeUnit.SECONDS.toMillis(1))
71+
remainingMs -= next
72+
delay(next)
73+
}
8274
delayMs = min(delayMs * backOffFactor, backOffLimitMs) + (random.nextGaussian() * delayMs * backOffJitter).toLong()
8375
}
8476
}

0 commit comments

Comments
 (0)