Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handler to run task every 5 seconds Kotlin

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

like image 958
Ryan Dailey Avatar asked Jul 24 '17 18:07

Ryan Dailey


People also ask

How do you call every 10 seconds on Android?

This example demonstrates how do I run a method every 10 seconds in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

How do you use kotlin handler postDelayed?

The postDelayed method takes two parameters Runnable and delayMillis . It adds the Runnable to the thread's message queue to be run after the specified amount of time elapses. The Runnable will execute on the thread to which this handler is attached.


4 Answers

Since you can't reference a lambda you're currently in, and you can't reference the property you're defining while you're defining the lambda you're assigning to it, the best solution here is an object expression:

val runnableCode = object: Runnable {
    override fun run() {
        handler.postDelayed(this, 5000)
    }
}

Assuming that this property is not a var because you actually want to change it while this self-calling is happening.

like image 170
zsmb13 Avatar answered Oct 23 '22 08:10

zsmb13


Simply Use fixedRateTimer

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

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

like image 32
Morteza Rastgoo Avatar answered Oct 23 '22 07:10

Morteza Rastgoo


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)
}
like image 5
DevPolarBear Avatar answered Oct 23 '22 08:10

DevPolarBear


As Kotlin does not yet allow recursive lambdas (see KT-10350), you must use other constructs, such as object expressions as in @zsmb13's answer, or ordinary functions as below

fun StartTimer() {
    Timer_Preview.postDelayed(Runnable { runnable() }, 5000)
}

fun runnable() {
    //Code here

    // Run code again after 5 seconds
    Timer_Preview.postDelayed(Runnable { runnable() }, 5000)
}

However, in your particular case, it looks like you could just call StartTimer() again to re-arm the timer, assuming it doesn't do anything else:

private val RunnableCode = Runnable {
    //Code here

    //Run code again after 5 seconds
    StartTimer()
}
like image 3
ephemient Avatar answered Oct 23 '22 08:10

ephemient