From e5e8bff6ab696070a797fd8a190265c91ab27580 Mon Sep 17 00:00:00 2001 From: schroda <50052685+schroda@users.noreply.github.com> Date: Mon, 24 Jul 2023 11:52:23 +0200 Subject: [PATCH] Trigger task on first execution after rescheduling When rescheduling a task, the first execution isn't based on the current time plus the interval, but instead it is based on the remaining time till the next execution using the old interval plus the time difference of the old and the new interval. Thus, the first execution with the new interval might take less time than the actual new interval. In this case, the task didn't get executed due to it being incorrectly considered a "catchup execution", since the time since the last execution was less than the actual interval. --- .../main/kotlin/suwayomi/tachidesk/util/HAScheduler.kt | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/server/src/main/kotlin/suwayomi/tachidesk/util/HAScheduler.kt b/server/src/main/kotlin/suwayomi/tachidesk/util/HAScheduler.kt index 83cf205036..b12f7260a3 100644 --- a/server/src/main/kotlin/suwayomi/tachidesk/util/HAScheduler.kt +++ b/server/src/main/kotlin/suwayomi/tachidesk/util/HAScheduler.kt @@ -128,9 +128,10 @@ object HAScheduler { ) } - private fun createTimerTask(interval: Long, execute: () -> Unit): TimerTask { + private fun createTimerTask(interval: Long, execute: () -> Unit, initialDelay: Long = interval): TimerTask { return object : TimerTask() { - var lastExecutionTime: Long = 0 + val elapsedIntervalTime = interval + initialDelay + var lastExecutionTime: Long = System.currentTimeMillis() - elapsedIntervalTime override fun run() { // If a task scheduled via "Timer::scheduleAtFixedRate" is delayed for some reason, the Timer will @@ -173,12 +174,11 @@ object HAScheduler { fun reschedule(taskId: String, interval: Long) { val task = deschedule(taskId) ?: return - val timerTask = createTimerTask(interval, task.execute) - val timeToNextExecution = task.getTimeToNextExecution() val intervalDifference = interval - task.interval val remainingTimeTillNextExecution = (timeToNextExecution + intervalDifference).coerceAtLeast(0) + val timerTask = createTimerTask(interval, task.execute, initialDelay = remainingTimeTillNextExecution) scheduledTasks.add(HATask(taskId, interval, task.execute, timerTask, task.name, initialDelay = remainingTimeTillNextExecution)) timer.scheduleAtFixedRate(timerTask, remainingTimeTillNextExecution, interval) }