How to call a function after delay in Kotlin?

kotlin delay coroutine
kotlin delay ui
kotlin coroutines timer
kotlin pause function
kotlin wait for thread to finish
kotlin run on ui thread
runnable kotlin
kotlin repeat function every second

As the title, is there any way to call a function after delay (1 second for example) in Kotlin?

You can use Schedule

inline fun Timer.schedule(
    delay: Long, 
    crossinline action: TimerTask.() -> Unit
): TimerTask (source)

example (thanks @Nguyen Minh Binh - found it here:

import java.util.Timer
import kotlin.concurrent.schedule

Timer("SettingUp", false).schedule(500) { 

Kotlin: How to Call Function After Delay - Ogulcan Orhan, To make the long story short: Sometimes we need to delay some function call. In Java, you may already know, we use Handler().postDelayed  NOTE: Refer Kotlin Coroutines Delay Job or Setup Android Kotlin Coroutines (1.1) With Coroutine Scope. ️ Is this article helpful? Buy me a coffee ☕ or support my work to keep this space 🖖 and ad-free.

There is also an option to use Handler -> postDelayed

                }, 1000)

Kotlin Coroutines, Since delay is a suspending function, call to delay results in non-blocking suspension thereby allowing the other Coroutine to execute. After 5 seconds when  There are two approaches to making computation code cancellable. The first one is to periodically invoke a suspending function that checks for cancellation. There is a yield function that is a good choice for that purpose. The other one is to explicitly check the cancellation status.

Many Ways
1. Using Handler class
    TODO("Do something")
    }, 2000)
2. Using Timer class
Timer().schedule(object : TimerTask() {
    override fun run() {
        TODO("Do something")
}, 2000)


Timer().schedule(timerTask {
    TODO("Do something")
}, 2000)


Timer().schedule(2000) {
    TODO("Do something")
3. Using Executors class
    TODO("Do something")
}, 2, TimeUnit.SECONDS)

Delay a task - Support, For example, in while (true) { delay(0.5f) { foo() } }. The foo method must never be called because there is not enough time between each call. How to call a user defined function in kotlin? While creating a function, we assign some specified task that function will perform whenever it is called. Whenever a function is called, control is transferred to that function. Then, specified task is performed. After that, control is transferred back to the caller of the function.

You have to import the following two libraries:

import java.util.*
import kotlin.concurrent.schedule

and after that use it in this way:

    //do something

Cancellation and Timeouts, All the suspending functions in kotlinx.coroutines are cancellable. Run it to see that it continues to print "I'm sleeping" even after cancellation until the job the tracked one after delay, there is a ready to use withTimeout function that does it. Here, two arguments number1 and number2 of type Double are passed to the addNumbers() function during function call. These arguments are called actual arguments. result = addNumbers(number1, number2) The parameters n1 and n2 accepts the passed arguments (in the function definition). These arguments are called formal arguments (or parameters).

You could launch a coroutine, delay it and then call the function:

 /*GlobalScope.*/launch {

If you are outside of a class or object prepend GlobalScope to let the coroutine run there, otherwise it is recommended to implement the CoroutineScope in the surrounding class, which allows to cancel all coroutines associated to that scope if necessary.

Basics, That is because delay is a special suspending function that does not block a thread, but The main thread invoking runBlocking blocks until the coroutine inside Note that right after "Task from coroutine scope" message, while waiting for  Composing Suspending Functions. This section covers various approaches to composition of suspending functions. Sequential by default. Assume that we have two suspending functions defined elsewhere that do something useful like some kind of remote service call or computation.

How to call a method after a delay in Android, In Kotlin try: Handler().postDelayed({. //Do something after 5000ms. }, 5000). And, In Java try: final Handler handler = new Handler();. handler. inline fun Timer. schedule ( delay: Long, period: Long, crossinline action: TimerTask. ( ) -> Unit ) : TimerTask Schedules an action to be executed periodically, starting after the specified delay (expressed in milliseconds) and with the interval of period milliseconds between the end of the previous task and the start of the next one.

Using the Timer and TimerTask Classes, is an example of using a timer to perform a task after a delay: import java.util. The run method contains the code that performs the task. In this example, the  The UI thread already comes with a Looper, so you can just make a new Handler() on the UI thread and post() Runnables directly to it. These Runnables execute on the UI thread. To have Runnables execute on another thread, you need to make a new thread, then Looper.prepare(), make a new Handler() and then Looper.loop().

Timer, kotlin.Any. ↳, java.util.Timer By default, the task execution thread does not run as a daemon thread, so it is capable of keeping an application from Schedules the specified task for execution after the specified delay. Possible duplicate of How to call a function after delay in Kotlin? – nologin Apr 8 '19 at 10:14 The runOnUiThread is necessary because the UI can only be manipulated from a UI thread, and the callback happens in a temporary background thread.

  • Thanks! Super easy. Found an example here… Timer("SettingUp", false).schedule(500) { doSomething() }
  • It does compile, if you add these two imports: import java.util.Timer and import kotlin.concurrent.schedule
  • @Matias Elorriaga, for me, putting this on a new brand file doesn't compile, even adding the imports Customizer said
  • you don't need to put it on a file, that method is part of stdlib, follow the link in the first line of the answer,
  • I originally thought this wouldn't compile even after importing kotlin.concurrent.schedule, because Kotlin merely complained of a signature mismatch, but then I realized I was trying to pass an Int instead of a Long. It compiled after correcting that.
  • Please add that it is only available on android, since the question asks for a general kotlin method (although it does have the Android tag)
  • It's not constructive from your side. As a result when users will search android tag might think that this is wrong answer.
  • For Android, it's better to use Handler than Timer :
  • I think, you should add a code for removing handlers after activity/fragment finish.
  • This will not run on the UI thread if you intended on doing that.
  • and what do you think is the best solution here?
  • Thanks! Strange, that coroutines were mentioned only in 2018.
  • @coolMind they are stable since a few months, so they are quite new ...