1+ /*
2+ * Copyright 2025 Lambda
3+ *
4+ * This program is free software: you can redistribute it and/or modify
5+ * it under the terms of the GNU General Public License as published by
6+ * the Free Software Foundation, either version 3 of the License, or
7+ * (at your option) any later version.
8+ *
9+ * This program is distributed in the hope that it will be useful,
10+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
11+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+ * GNU General Public License for more details.
13+ *
14+ * You should have received a copy of the GNU General Public License
15+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
16+ */
17+
18+ package com.lambda.util
19+
20+ /* *
21+ * A utility class to manage time-based operations, such as delays and periodic tasks.
22+ */
23+ class SimpleTimer {
24+ /* *
25+ * Stores the timestamp of the last timing event.
26+ */
27+ private var lastTiming = 0L
28+
29+ /* *
30+ * Checks if the specified amount of time has passed since the last timing event.
31+ *
32+ * @param time the time interval in milliseconds to check.
33+ * @return `true` if the current time exceeds `lastTiming + time`, `false` otherwise.
34+ */
35+ fun timePassed (time : Long ): Boolean =
36+ currentTime - lastTiming > time
37+
38+ /* *
39+ * Checks if the specified time has passed and resets the timer if true.
40+ *
41+ * @param time the time interval in milliseconds to check.
42+ * @return `true` if the time has passed and the timer was reset, `false` otherwise.
43+ */
44+ fun delayIfPassed (time : Long ): Boolean =
45+ timePassed(time).apply {
46+ if (this ) reset()
47+ }
48+
49+ /* *
50+ * Executes a given block of code if the specified time has passed since the last timing event.
51+ * Optionally resets the timer after execution.
52+ *
53+ * @param time the time interval in milliseconds to check.
54+ * @param reset whether to reset the timer after running the block. Defaults to `true`.
55+ * @param block the code block to execute if the time has passed.
56+ */
57+ fun runIfPassed (time : Long , reset : Boolean = true, block : () -> Unit ) =
58+ timePassed(time).apply {
59+ if (! this ) return @apply
60+ if (reset) reset()
61+
62+ block()
63+ }
64+
65+ /* *
66+ * Resets the timer by updating the last timing event to the current time.
67+ *
68+ * @param additionalDelay an additional delay in milliseconds to add to the current time. Defaults to `0`.
69+ */
70+ fun reset (additionalDelay : Long = 0L) {
71+ lastTiming = currentTime + additionalDelay
72+ }
73+
74+ companion object {
75+ private val currentTime get() = System .currentTimeMillis()
76+ }
77+ }
0 commit comments