Created
June 26, 2021 18:20
-
-
Save themisir/324c379ee16a82b8dc18feca74f1240a to your computer and use it in GitHub Desktop.
Simple abstraction on top of java.util.Timer for scheduling one time and periodic actions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.themisir.utils | |
import java.util.* | |
class Task(private val timer: Timer) { | |
companion object { | |
fun schedule(delay: Long, func: () -> Unit): Task { | |
return Task(Timer().also { | |
it.schedule(createTimerTask(func), delay) | |
}) | |
} | |
fun periodic(delay: Long, period: Long, func: () -> Unit): Task { | |
return Task(Timer().also { | |
it.scheduleAtFixedRate(createTimerTask(func), delay, period) | |
}) | |
} | |
private fun createTimerTask(func: () -> Unit): TimerTask { | |
return object : TimerTask() { | |
override fun run() { | |
func() | |
} | |
} | |
} | |
} | |
fun cancel() { | |
timer.cancel() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment