Skip to content

Instantly share code, notes, and snippets.

@Splagoon
Created November 11, 2014 18:50
Show Gist options
  • Save Splagoon/9fcd007741afee62edfe to your computer and use it in GitHub Desktop.
Save Splagoon/9fcd007741afee62edfe to your computer and use it in GitHub Desktop.
Time magics with Kotlin
import java.util.Date
import kotlin.concurrent.*
fun at(date: Date, func: () -> Unit) {
val waitTime = date.getTime() - Date().getTime()
thread {
Thread.sleep(waitTime)
func()
}
}
fun every(interval: TimeSpan, func: () -> Unit) {
thread {
while (true) {
Thread.sleep(interval.milliseconds)
func()
}
}
}
data class TimeSpan(val milliseconds: Long) {
fun plus(other: TimeSpan) = TimeSpan(milliseconds + other.milliseconds)
fun plus(other: Date) = Date(milliseconds + other.getTime())
fun and(other: TimeSpan): TimeSpan = this + other
fun from(date: Date): Date = this + date
}
val Int.seconds: TimeSpan get() = TimeSpan(this * 1000L)
val Int.second: TimeSpan get() = this.seconds
val Int.minutes: TimeSpan get() = TimeSpan(this * 60000L)
val Int.minute: TimeSpan get() = this.minutes
val now: Date get() = Date()
fun main(args: Array<String>) {
at (1.minute and 10.seconds from now) {
println("Excellent.")
}
every (15.seconds) {
println("Beep.")
}
println("Blocking...")
while (true) {}
}
@mohammedh123
Copy link

( ͝° ͜ʖ ͝°)

@emilh91
Copy link

emilh91 commented Nov 11, 2014

( ͝° ͜ʖ ͝°)

@dev-drprasad
Copy link

is there any problem with while (true) {} line. will it eat CPU resources ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment