Skip to content

Instantly share code, notes, and snippets.

@themisir
Created June 26, 2021 18:20
Show Gist options
  • Save themisir/324c379ee16a82b8dc18feca74f1240a to your computer and use it in GitHub Desktop.
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
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