komikku/app/src/main/java/exh/eh/EHentaiThrottleManager.kt

41 lines
1 KiB
Kotlin
Raw Normal View History

package exh.eh
import kotlinx.coroutines.delay
import kotlin.time.Duration
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
class EHentaiThrottleManager(
private val max: Duration = THROTTLE_MAX,
private val inc: Duration = THROTTLE_INC
) {
private var lastThrottleTime = Duration.ZERO
var throttleTime = Duration.ZERO
private set
suspend fun throttle() {
// Throttle requests if necessary
val now = System.currentTimeMillis().milliseconds
val timeDiff = now - lastThrottleTime
2020-05-02 06:46:24 +02:00
if (timeDiff < throttleTime) {
delay(throttleTime - timeDiff)
2020-05-02 06:46:24 +02:00
}
2020-05-02 06:46:24 +02:00
if (throttleTime < max) {
throttleTime += inc
2020-05-02 06:46:24 +02:00
}
lastThrottleTime = System.currentTimeMillis().milliseconds
}
fun resetThrottle() {
lastThrottleTime = Duration.ZERO
throttleTime = Duration.ZERO
}
companion object {
val THROTTLE_MAX = 5.5.seconds
val THROTTLE_INC = 20.milliseconds
}
}