Configurable throttle period

pull/1061/head
Alex Baker 4 years ago
parent 24fd1acb68
commit e3bcc2f7c9

@ -44,7 +44,7 @@ class NotificationManager @Inject constructor(
private val reminderService: ReminderService) {
private val notificationManagerCompat = NotificationManagerCompat.from(context)
private val colorProvider = ColorProvider(context, preferences)
private val throttle = Throttle(NOTIFICATIONS_PER_SECOND)
private val throttle = Throttle(NOTIFICATIONS_PER_SECOND, tag = "NOTIFY")
private val queue = NotificationLimiter(MAX_NOTIFICATIONS)
@SuppressLint("CheckResult")

@ -1,22 +1,26 @@
package org.tasks.notifications
import kotlinx.coroutines.delay
import org.tasks.time.DateTimeUtils
import org.tasks.time.DateTimeUtils.currentTimeMillis
import timber.log.Timber
internal class Throttle constructor(
ratePerSecond: Int,
ratePerPeriod: Int,
private val periodMillis: Long = 1000,
private val tag: String = "",
private val sleeper: suspend (Long) -> Unit = { delay(it) }) {
private val throttle: LongArray = LongArray(ratePerSecond)
private val throttle: LongArray = LongArray(ratePerPeriod)
private var oldest = 0
@Synchronized
suspend fun run(runnable: suspend () -> Unit) {
val sleep = throttle[oldest] - (DateTimeUtils.currentTimeMillis() - 1000)
val sleep = throttle[oldest] - (currentTimeMillis() - periodMillis)
if (sleep > 0) {
Timber.d("$tag: Throttled for ${sleep}ms")
sleeper.invoke(sleep)
}
runnable.invoke()
throttle[oldest] = DateTimeUtils.currentTimeMillis()
throttle[oldest] = currentTimeMillis()
oldest = (oldest + 1) % throttle.size
}
}
Loading…
Cancel
Save