首页 > 解决方案 > Kotin 应用程序在使用 fixedRateTimer 时不会停止(即使窗口关闭)

问题描述

我在 Kotlin 中有一个简单的应用程序,它绘制一个矩形,然后使用 fixedRateTimer 每秒 30 次更新矩形的位置。我遇到的问题是,当我关闭显示应用程序继续运行的矩形的窗口时,我必须按下 Intellij 内的红色方块才能真正停止它。

我尝试在关闭窗口之前取消 fixedRateTimer,但应用程序仍在运行,它似乎没有做任何事情。如果我在没有 fixedRateTimer 的情况下运行应用程序,它只会显示正方形,然后当我关闭窗口时它会停止应用程序。

import javafx.scene.paint.Color
import tornadofx.*
import kotlin.concurrent.fixedRateTimer

class MyApp: App(MyView::class)

class MyView : View() {

    override val root = stackpane {
        group {
            rectangle {
                fill = Color.LIGHTGRAY
                width = 600.0
                height = 480.0
            }

            val myRect = rectangle {
                fill = Color.BLUEVIOLET
                width = 30.0
                height = 30.0
                x = 100.0
                y = 100.0
            }

            fixedRateTimer("default", false, 0L, 1000/30) {
                myRect.x += 1
                if(myRect.x > 200) this.cancel()
            }
        }
    }
}

标签: kotlintornadofx

解决方案


您正在取消 TimerTask,但不是计时器。要么通过daemon = true创建一个守护线程,要么确保保存Timer从调用返回的实例fixedRateTimer(),并在某个时候调用cancel它以在退出之前停止非守护线程运行计时器。

JVM 会在有守护线程运行时退出,但在有非守护线程时不会退出。


推荐阅读