Handler to run task every 5 seconds Kotlin

Viewed 20957

I would like to run a certain code every 5 seconds. I am having trouble achieving this with a handler. How can this be done in Kotlin? Here is what I have so far. Also to note, the variable Timer_Preview is a Handler.

My Code

5 Answers

Simply Use fixedRateTimer

 fixedRateTimer("timer",false,0,5000){
        this@MainActivity.runOnUiThread {
            Toast.makeText(this@MainActivity, "text", Toast.LENGTH_SHORT).show()
        }
    }

Change initial delay by setting another value for the third parameter.

I recommended SingleThread because it is very useful. If you would like to do job for each second, you can set because parameters of it:

Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit);

TimeUnit values are: NANOSECONDS, MICROSECONDS, MILLISECONDS, SECONDS, MINUTES, HOURS, DAYS.

Example:

private fun mDoThisJob(){

    Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate({
        //TODO: You can write your periodical job here..!

    }, 1, 1, TimeUnit.SECONDS)
}

You can do this with simple functions:

private fun waitToDoSomethingRecursively() {
    handler.postDelayed(::doSomethingRecursively, 5000)
}

private fun doSomethingRecursively () {
    ...
    waitToDoSomethingRecursively()
}
Related