Created
November 11, 2014 18:50
-
-
Save Splagoon/9fcd007741afee62edfe to your computer and use it in GitHub Desktop.
Time magics with Kotlin
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
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) {} | |
} |
( ͝° ͜ʖ ͝°)
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
( ͝° ͜ʖ ͝°)