-
-
Notifications
You must be signed in to change notification settings - Fork 800
Expand file tree
/
Copy pathRecurringTask.kt
More file actions
45 lines (39 loc) · 1.46 KB
/
RecurringTask.kt
File metadata and controls
45 lines (39 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package org.wikipedia.recurring
import org.wikipedia.settings.Prefs
import org.wikipedia.util.log.L
import java.util.Date
import kotlin.math.max
import kotlin.math.min
/**
* Represents a task that needs to be run periodically.
*
* Usually an expensive task, that is run Async. Do not do anything
* that requires access to the UI thread on these tasks.
*
* Since it is an expensive task, there's a separate method that detects
* if the task should be run or not, and then runs it if necessary. The
* last run times are tracked automatically by the base class.
*/
abstract class RecurringTask {
suspend fun runIfNecessary() {
val lastRunDate = lastRunDate
val lastExecutionLog = "$name. Last execution was $lastRunDate."
if (shouldRun(lastRunDate)) {
L.d("Executing recurring task, $lastExecutionLog")
run(lastRunDate)
Prefs.setLastRunTime(name, absoluteTime)
} else {
L.d("Skipping recurring task, $lastExecutionLog")
}
}
protected abstract fun shouldRun(lastRun: Date): Boolean
protected abstract suspend fun run(lastRun: Date)
protected abstract val name: String
protected val absoluteTime: Long
get() = System.currentTimeMillis()
private val lastRunDate: Date
get() = Date(Prefs.getLastRunTime(name))
protected fun millisSinceLastRun(lastRun: Date): Long {
return min(Long.MAX_VALUE, max(0, absoluteTime - lastRun.time))
}
}