blob: 3618a3b60c201d1fa71af52c8c991befa1736469 [file] [log] [blame]
Roman Elizarovf16fd272017-02-07 11:26:00 +03001/*
Roman Elizarov1f74a2d2018-06-29 19:19:45 +03002 * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
Roman Elizarovf16fd272017-02-07 11:26:00 +03003 */
4
Roman Elizarovb3d55a52017-02-03 12:47:21 +03005// This file was automatically generated from coroutines-guide.md by Knit tool. Do not edit.
Roman Elizarov0950dfa2018-07-13 10:33:25 +03006package kotlinx.coroutines.guide.cancel02
Roman Elizarov7deefb82017-01-31 10:33:17 +03007
Roman Elizarov0950dfa2018-07-13 10:33:25 +03008import kotlinx.coroutines.*
Roman Elizarov7deefb82017-01-31 10:33:17 +03009
Prendota65e6c8c2018-10-17 11:51:08 +030010fun main() = runBlocking {
11//sampleStart
Roman Elizarov7afb62e2018-07-23 20:32:48 +030012 val startTime = timeSource.currentTimeMillis()
Roman Elizarovdc29b072018-09-11 18:42:03 +030013 val job = launch(Dispatchers.Default) {
Roman Elizarov24cd6542017-08-03 21:20:04 -070014 var nextPrintTime = startTime
Roman Elizarov7deefb82017-01-31 10:33:17 +030015 var i = 0
Roman Elizarov8b38fa22017-09-27 17:44:31 +030016 while (i < 5) { // computation loop, just wastes CPU
Roman Elizarov24cd6542017-08-03 21:20:04 -070017 // print a message twice a second
Roman Elizarov7afb62e2018-07-23 20:32:48 +030018 if (timeSource.currentTimeMillis() >= nextPrintTime) {
Roman Elizarov7deefb82017-01-31 10:33:17 +030019 println("I'm sleeping ${i++} ...")
Roman Elizarov35d2c342017-07-20 14:54:39 +030020 nextPrintTime += 500L
Roman Elizarov7deefb82017-01-31 10:33:17 +030021 }
22 }
23 }
24 delay(1300L) // delay a bit
Roman Elizarov1293ccd2017-02-01 18:49:54 +030025 println("main: I'm tired of waiting!")
Roman Elizarov8b38fa22017-09-27 17:44:31 +030026 job.cancelAndJoin() // cancels the job and waits for its completion
Roman Elizarov1293ccd2017-02-01 18:49:54 +030027 println("main: Now I can quit.")
Prendota65e6c8c2018-10-17 11:51:08 +030028//sampleEnd
Roman Elizarovb3d55a52017-02-03 12:47:21 +030029}