防止任务在开始之前运行

问题描述 投票:0回答:1

您好,我创建了一个 TimerTask,设置为在 5 秒后启动,但在我的应用程序中,用户可以执行某些操作来阻止此任务运行。如何在计时器结束之前取消任务并防止其发生?

这是我的代码:

val time = Timer("Timer",false)

    Timber.tag("COMPOSABLE23").d(fingerprintFingerCount.name)
    fun test(){
        Timber.tag("COMPOSABLE24").d(fingerprintFingerCount.name)
        if (fingerprintFingerCount.name == FingerprintScanStatus.ScanFew.name){
            Timber.tag("COMPOSABLE2").d("Manger encore")
        }
    }

        if (fingerprintFingerCount.name == FingerprintScanStatus.ScanFew.name){
            Timber.tag("COMPOSABLE2").d("Manger")
            time.schedule(5000){
                test()
            }
        }else if(fingerprintFingerCount.name == FingerprintScanStatus.ScanNotStarted.name){
            time.cancel()
        }
android kotlin timer scheduled-tasks
1个回答
0
投票

TimerTask 有一个

var
属性作为可空类型。出于稳健性/组织的原因,也将计时器放在一个属性中。

private val timer = Timer("Timer", false)
private var timerTask: TimerTask? = null

创建 TimerTask 时,请取消之前的任何一个,以防万一。通过设置属性来创建计时器。然后安排一下。这样,您就可以在属性中保留对它的引用,以便以后需要时可以取消它。

timerTask?.cancel()
timerTask = object: TimerTask() {
    override fun run() {
        test()
    }
}
timer.schedule(timerTask, delay = 5000L)

当您需要取消时,只需拨打

timerTask?.cancel()
即可。

© www.soinside.com 2019 - 2024. All rights reserved.