Skip to content

Commit 41c5192

Browse files
authored
Merge pull request #846 from hangga/repeat-task
KTLN-435 - Scheduling Repeating Task in Kotlin
2 parents a78ec2a + ab42693 commit 41c5192

File tree

3 files changed

+85
-0
lines changed

3 files changed

+85
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package com.baeldung.schedulingrepeatingtask
2+
3+
import java.util.concurrent.Executors
4+
import java.util.concurrent.TimeUnit
5+
6+
fun main(){
7+
val scheduler = Executors.newScheduledThreadPool(1)
8+
scheduler.scheduleAtFixedRate({
9+
println("Complex task completed!")
10+
}, 0, 1, TimeUnit.SECONDS)
11+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package com.baeldung.schedulingrepeatingtask
2+
3+
import java.util.Timer
4+
import kotlin.concurrent.schedule
5+
6+
fun main(){
7+
val timer = Timer()
8+
timer.schedule(0, 1000) {
9+
println("Timer ticked!")
10+
}
11+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package com.baeldung.schedulingrepeatingtask
2+
3+
import kotlinx.coroutines.*
4+
import kotlinx.coroutines.flow.flow
5+
import kotlinx.coroutines.flow.flowOf
6+
import kotlinx.coroutines.flow.take
7+
import kotlinx.coroutines.flow.transform
8+
import org.junit.jupiter.api.Assertions.assertEquals
9+
import org.junit.jupiter.api.Test
10+
import org.junit.jupiter.api.assertThrows
11+
import kotlin.time.Duration.Companion.milliseconds
12+
import kotlin.time.Duration.Companion.seconds
13+
14+
class SchedulingRepeatingTaskUnitTest {
15+
16+
@Test
17+
fun `using repeat and delay`() = runBlocking {
18+
var count = 0
19+
repeat(10) {
20+
count++
21+
println("Timer ticked! $count")
22+
delay(1000.milliseconds)
23+
}
24+
25+
assertEquals(10, count)
26+
}
27+
28+
@Test
29+
fun `using withTimeout`(): Unit = runBlocking {
30+
var count = 0
31+
assertThrows<TimeoutCancellationException> {
32+
withTimeout(5000.milliseconds) {
33+
while (true) {
34+
count++
35+
println("Waiting for timeout")
36+
delay(1000.milliseconds)
37+
}
38+
}
39+
}
40+
assertEquals(5, count)
41+
}
42+
43+
@Test
44+
fun `using flow collect take`() = runBlocking {
45+
46+
val flow = flow {
47+
while (true) {
48+
emit(Unit)
49+
delay(1000.milliseconds)
50+
}
51+
}
52+
53+
var count = 0
54+
55+
flow.take(10).collect{
56+
count++
57+
println(count)
58+
}
59+
60+
assertEquals(10, count)
61+
}
62+
63+
}

0 commit comments

Comments
 (0)