Search code examples
androidkotlintimerscheduled-tasks

Prevent a task to run before it started


Hello I've created a TimerTask that is setup to be launched after 5s but in my app the user can do something that must prevent this task to run. How do i cancel the task before the timer ends and prevent it from ever happening?

Here is my code:

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()
        }

Solution

  • Have a var property for the TimerTask as a nullable type. And keep your timer in a property, too, for robustness/organization reasons.

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

    When you create the TimerTask, cancel any previous one just in case. Create the timer by setting the property. Then schedule it. This way, you are keeping a reference to it in the property so you can cancel it later if you need to.

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

    When you need to cancel it, you just need to call timerTask?.cancel().