我试图了解哪种方法是在Kotlin中按计划的速率启动异步作业的最佳方法,而应用程序通常正在运行它的正常任务。假设我有一个简单的应用程序,该应用程序每秒仅打印“...”,但是每5秒我要另一个作业/线程/协程(最适合)打印“您有消息!”。对于异步作业,我有一个NotificationProducer
类,它看起来像这样。
class NotificationProducer {
fun produce() {
println("You have a message!")
}
}
然后,我的主要方法如下所示。
while (true) {
println("...")
sleep(1000)
}
我应该使用
GlobalScope.async
,Timer().schedule(...)
还是一些Quartz作业来实现我想要的?任何建议都受到高度赞赏。关键是通知必须来自另一个类(例如NotificationProducer)
最佳答案
如果我正确理解了这个问题,可以使用Kotlin Coroutines如下实现:
class Presenter : CoroutineScope { // implement CoroutineScope to create local scope
private var job: Job = Job()
override val coroutineContext: CoroutineContext
get() = Dispatchers.Default + job
// this method will help to stop execution of a coroutine.
// Call it to cancel coroutine and to break the while loop defined in the coroutine below
fun cancel() {
job.cancel()
}
fun schedule() = launch { // launching the coroutine
var seconds = 1
val producer = NotificationProducer()
while (true) {
println("...")
delay(1000)
if (seconds++ == 5) {
producer.produce()
seconds = 1
}
}
}
}
然后,您可以使用
Presenter
类的实例启动协程并停止协程:val presenter = Presenter()
presenter.schedule() // calling `schedule()` function launches the coroutine
//...
presenter.cancel() // cancel the coroutine when you need
关于asynchronous - Kotlin中的异步预定作业,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54852812/