-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
0f3c27f
commit dd68e30
Showing
1 changed file
with
12 additions
and
1 deletion.
There are no files selected for viewing
13 changes: 12 additions & 1 deletion
13
...in-crums/jeorg-kotlin-crums-3/src/main/kotlin/org/jesperancinha/ktd/crums3/TimedTimers.kt
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,36 +1,47 @@ | ||
package org.jesperancinha.ktd.crums3 | ||
|
||
import arrow.atomic.AtomicInt | ||
import java.lang.Thread.sleep | ||
import java.time.LocalDateTime | ||
import java.util.* | ||
|
||
|
||
class SleepingTimerTask : TimerTask() { | ||
|
||
val counter = AtomicInt(0) | ||
|
||
/** | ||
* Explicitly blocking to simulate task | ||
* This tasks takes 1 second to complete | ||
*/ | ||
override fun run() { | ||
println("Task started at ${LocalDateTime.now()}") | ||
sleep(1000) | ||
counter.addAndGet(1) | ||
callLongProcess() | ||
println("Task ended at ${LocalDateTime.now()}") | ||
} | ||
|
||
private fun callLongProcess() { | ||
sleep(5000) | ||
} | ||
|
||
companion object { | ||
|
||
/** | ||
* Each task will run for 1 second and will start every 2 seconds | ||
*/ | ||
@JvmStatic | ||
fun main(args: Array<String>) { | ||
val timerTask: TimerTask = SleepingTimerTask() | ||
val timerTask = SleepingTimerTask() | ||
val timer = Timer(true) | ||
timer.scheduleAtFixedRate(timerTask, 0, 2_000) | ||
println("TimerTask has started and now we wait 10 seconds") | ||
println("Normally it should count 5 calls, but maybe not now, because of the long call") | ||
sleep(10_000) | ||
timer.cancel() | ||
println("TimerTask has been cancelled") | ||
println("${timerTask.counter} calls have been made!") | ||
} | ||
} | ||
} |