Skip to content

Commit

Permalink
Trigger task on first execution after rescheduling
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
schroda committed Jul 24, 2023
1 parent 0a289ee commit e5e8bff
Showing 1 changed file with 4 additions and 4 deletions.
8 changes: 4 additions & 4 deletions server/src/main/kotlin/suwayomi/tachidesk/util/HAScheduler.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
}
Expand Down

0 comments on commit e5e8bff

Please sign in to comment.