aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/at/hannibal2/skyhanni/utils/DelayedRun.kt
blob: 284946072b1121de1790a7aa6732f41f8ecdb19a (plain)
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
package at.hannibal2.skyhanni.utils

import at.hannibal2.skyhanni.utils.LorenzUtils.drainTo
import java.util.concurrent.ConcurrentLinkedQueue
import kotlin.time.Duration

object DelayedRun {
    private val tasks = mutableListOf<Pair<() -> Any, SimpleTimeMark>>()
    private val futureTasks = ConcurrentLinkedQueue<Pair<() -> Any, SimpleTimeMark>>()

    fun runDelayed(duration: Duration, run: () -> Unit) {
        futureTasks.add(Pair(run, SimpleTimeMark.now() + duration))
    }

    /** Runs in the next full Tick so the delay is between 50ms to 100ms**/
    fun runNextTick(run: () -> Unit) {
        futureTasks.add(Pair(run, SimpleTimeMark.farPast()))
    }

    fun checkRuns() {
        tasks.removeIf { (runnable, time) ->
            val inPast = time.isInPast()
            if (inPast) {
                runnable()
            }
            inPast
        }
        futureTasks.drainTo(tasks)
    }
}