asynchronous - Kotlin中的异步预定作业

标签 asynchronous kotlin quartz-scheduler

我试图了解哪种方法是在Kotlin中按计划的速率启动异步作业的最佳方法,而应用程序通常正在运行它的正常任务。假设我有一个简单的应用程序,该应用程序每秒仅打印“...”,但是每5秒我要另一个作业/线程/协程(最适合)打印“您有消息!”。对于异步作业,我有一个NotificationProducer类,它看起来像这样。

class NotificationProducer {

    fun produce() {
        println("You have a message!")
    }
} 

然后,我的主要方法如下所示。
    while (true) {
        println("...")
        sleep(1000)
    }

我应该使用GlobalScope.asyncTimer().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/

相关文章:

javascript - javascript中for循环内的异步函数调用

javascript - 在异步函数调用之外使用变量

android - 我如何在没有初始化的情况下在 Kotlin 中声明一个可以从类中的任何 fun 访问的 val?

xaml - Windows 8. Metro 应用程序。 XAML 异步绑定(bind)

android - Kotlin 运行时错误 kotlin.Any 未找到

android - 如何在 Kotlin 中构建基于 MutableList 的列表?

java - Spring引导与CalendarIntervalTrigger程序

linux - 用于在不同时间以不同时间间隔运行作业的 Cron 表达式

mule - 有条件地运行 Mule Quartz

twitter-bootstrap - 如何使用 $resource 填充 Angular UI Bootstrap typeahead