Skip to content

Commit

Permalink
Timeouts example
Browse files Browse the repository at this point in the history
  • Loading branch information
jesperancinha committed Jan 14, 2024
1 parent d2bf4b3 commit cb74b5b
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ class Main {
Delegates.main()
Account.main(emptyArray())
IndexSolutionForRIDHashes.main()
Timeouts.main()
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package org.jesperancinha.ktd

import java.lang.Thread.sleep
import java.util.*
import kotlin.system.measureTimeMillis


class Timeouts {

internal class TimeOutTask(f: () -> Unit) : TimerTask() {

val thread = Thread(f)
override fun run() {
thread.start()
}

override fun cancel(): Boolean {
super.cancel()
thread.interrupt()
return true
}
}

companion object {
@JvmStatic
fun main(args: Array<String> = emptyArray()) = measureTimeMillis {
val timer = Timer()
val scheduledFunction = { sleep(5000) }
runFunction(timer = timer, timeout = 1000, f = scheduledFunction)
}.let {
println(it)
}

private fun runFunction(timer: Timer, timeout:Long, f: () -> Unit) {
val timeOutTask = TimeOutTask(f)
timer.schedule(timeOutTask, 0)
sleep(timeout)
timeOutTask.cancel()
timer.cancel()
}
}
}

0 comments on commit cb74b5b

Please sign in to comment.