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

- 23,891
- 30
- 115
- 165
15 Answers
There is also an option to use Handler -> postDelayed
Handler().postDelayed({
//doSomethingHere()
}, 1000)

- 5,639
- 2
- 21
- 16
-
41Please add that it is only available on android, since the question asks for a general kotlin method (although it does have the Android tag) – Yoav Sternberg Apr 20 '17 at 13:43
-
7It's not constructive from your side. As a result when users will search android tag might think that this is wrong answer. – Bogdan Ustyak Apr 20 '17 at 20:27
-
13For Android, it's better to use Handler than Timer : https://stackoverflow.com/questions/20330355/timertask-or-handler – woprandi Apr 20 '18 at 13:54
-
I think, you should add a code for removing handlers after activity/fragment finish. – CoolMind Jan 30 '19 at 07:37
-
1This will not run on the UI thread if you intended on doing that. – Johann Aug 24 '19 at 06:37
-
4In Android, Handler is deprecated. any alternative? – CanCoder Dec 13 '21 at 03:12
-
I think for Android and Kotlin ist Coroutines the best alternative. https://kotlinlang.org/docs/coroutines-overview.html – dudi Dec 13 '21 at 07:32
-
2@leeCoder Use: `Handler(Looper.getMainLooper())` instead. `Handler()` call without looper is deprecated, but if you specify the Looper yourself it is all good. – Tom Raganowicz Jul 10 '22 at 10:18
-
`Handler.postDelayed` is Deprecated, you should use `Handler(Looper.getMainLooper()).postDelayed` – Hasan Mhd Amin Aug 10 '22 at 11:16
-
What about using Kotlin delay? – IgorGanapolsky Jun 08 '23 at 14:35
Many Ways
1. Using Handler
class
Handler().postDelayed({
TODO("Do something")
}, 2000)
2. Using Timer
class
Timer().schedule(object : TimerTask() {
override fun run() {
TODO("Do something")
}
}, 2000)
// Shorter
Timer().schedule(timerTask {
TODO("Do something")
}, 2000)
// Shortest
Timer().schedule(2000) {
TODO("Do something")
}
3. Using Executors
class
Executors.newSingleThreadScheduledExecutor().schedule({
TODO("Do something")
}, 2, TimeUnit.SECONDS)

- 57,232
- 27
- 203
- 212
-
4
-
3Probably the first one using a Handler. See https://stackoverflow.com/a/40339630/1159930 – Markymark Jan 24 '20 at 18:51
-
Can we do it synchronously , Handler is in Android package I believe. Is there any other way – Akshay Hazari Feb 22 '22 at 06:30
-
@AkshayHazari See his answer.. https://stackoverflow.com/a/52801912/6891563 – Khemraj Sharma Feb 22 '22 at 16:59
-
4Just to follow up on the comment regarding Handler().postDelayed being the best solution... that's deprecated now (at least in Android) and suggests Executors, so at least for Android I'd say that's the "best solution" (though Timer is also simple and straightforward) – anabi Apr 14 '22 at 07:18
-
You can use Schedule
inline fun Timer.schedule(
delay: Long,
crossinline action: TimerTask.() -> Unit
): TimerTask (source)
example (thanks @Nguyen Minh Binh - found it here: http://jamie.mccrindle.org/2013/02/exploring-kotlin-standard-library-part-3.html)
import java.util.Timer
import kotlin.concurrent.schedule
Timer("SettingUp", false).schedule(500) {
doSomething()
}

- 8,084
- 8
- 48
- 62

- 8,880
- 5
- 40
- 58
-
17Thanks! Super easy. Found an example here http://jamie.mccrindle.org/2013/02/exploring-kotlin-standard-library-part-3.html `Timer("SettingUp", false).schedule(500) { doSomething() }` – Nguyen Minh Binh Apr 11 '17 at 14:35
-
17It does compile, if you add these two imports: import java.util.Timer and import kotlin.concurrent.schedule – Customizer Dec 31 '17 at 00:29
-
3@Matias Elorriaga, for me, putting this on a new brand file doesn't compile, even adding the imports Customizer said – Sulfkain Jan 16 '18 at 09:09
-
3you 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, – Matias Elorriaga Jan 16 '18 at 13:38
-
-
2for those that would like to have it run at an interval: timer.scheduleAtFixedRate(0, inactivityHeartbeat) { //.... do stuff} – Bart Burg Sep 20 '18 at 11:00
-
4I 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. – Joe Lapp Apr 30 '19 at 15:19
-
Can someone show this as an example. Cut and pasted this and it does not compile had both imports too. Says the schedule needs a body on the inline function – JPM Jul 18 '19 at 19:46
-
-
Downvoted because it doesn't compile like many of the comments have already indicated. – Johann Aug 24 '19 at 06:35
-
@AndroidDev is part of the standard library, you don’t need to compile, just add the import.. – Matias Elorriaga Aug 24 '19 at 10:56
-
1@IgorGanapolsky - this code compiles fine on Kotlin 1.3.50. What's your error msg? You might have faced my initial problem: make sure the numeric value passed in (500) is a Long and not Int. You'll get a compile error if you do something like: Timer("SettingUp", false).schedule(500+x) {} where "x" is an Int you declared elsewhere. Declare x as a Long and you'll be fine, e.g., val x = 25L – Vahid Pazirandeh Nov 08 '19 at 19:28
-
that work great! Following question is how to insert my class scope inside of this. AKA replace ` doSomething()` with `this.myFunc()`? – Blue Bot Aug 23 '20 at 09:43
-
1
You could launch
a coroutine, delay
it and then call the function:
/*GlobalScope.*/launch {
delay(1000)
yourFn()
}
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.

- 132,000
- 20
- 149
- 151
-
-
@coolMind they are stable since a few months, so they are quite new ... – Jonas Wilms Jan 30 '19 at 09:52
-
-
CAUTION: This approach counts against the dispatcher's available parallelism even while the coroutine is suspended with `delay()`. I think using a Timer is a much safer Kotlin-generic option. – Jonn Apr 23 '23 at 10:07
val timer = Timer()
timer.schedule(timerTask { nextScreen() }, 3000)

- 997
- 2
- 11
- 23
-
1Can you please explain me why I there's need to write "timerTask" instead of just braces? – Hugo Passos Dec 22 '17 at 07:49
-
3I think you do. `Timer.schedule()` expects a `TimerTask` as it's first argument. `kotlin.concurrent.timerTask()` wraps the given lambda in a `TimerTask` instance. See here: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.concurrent/timer-task.html – Blieque Mar 27 '18 at 17:18
-
Also, the given example can be condensed to one line if the `Timer` object isn't going to be used more than once, e.g., `Timer().schedule(timerTask { ... }, 3000)`. A more Kotlin-friendly option is available too; see jonguer's answer. – Blieque Mar 27 '18 at 17:20
If you're using more recent Android APIs the Handler empty constructor has been deprecated and you should include a Looper. You can easily get one through Looper.getMainLooper()
.
Handler(Looper.getMainLooper()).postDelayed({
//Your code
}, 2000) //millis

- 5,194
- 5
- 32
- 48
If you are in a fragment with viewModel scope you can use Kotlin coroutines:
myViewModel.viewModelScope.launch {
delay(2000)
// DoSomething()
}

- 751
- 1
- 12
- 25
-
what dispatcher do you suggest to use here if the task does not do any api request? – paxcow Dec 23 '22 at 15:25
-
1@paxcow it depends, if its just for a testing use case you can use the Main. But in any other case, I'd always use IO because you are delaying a task, similar what we do with an API request. – Andy Dec 28 '22 at 15:52
-
Only specify dispatchers when you are calling blocking code, or when you're calling main-only code (like interacting with Views or LiveData and you aren't already on Dispatchers.Main). – Tenfour04 Apr 04 '23 at 12:42
A simple example to show a toast after 3 seconds :
fun onBtnClick() {
val handler = Handler()
handler.postDelayed({ showToast() }, 3000)
}
fun showToast(){
Toast.makeText(context, "Its toast!", Toast.LENGTH_SHORT).show()
}

- 2,602
- 1
- 21
- 36
If you are looking for generic usage, here is my suggestion:
Create a class named as Run
:
class Run {
companion object {
fun after(delay: Long, process: () -> Unit) {
Handler().postDelayed({
process()
}, delay)
}
}
}
And use like this:
Run.after(1000, {
// print something useful etc.
})

- 5,170
- 6
- 33
- 49
-
1
-
1@Ogulcan, more kotlinic lamda `Run.after(1000) { toRun() }`. Am I correct – binrebin Jul 15 '20 at 10:00
i suggest to use kotlin coroutine and if you want to cancel it. its simple and light weight.
fun repeatFun(): Job {
return coroutineScope.launch {
while(isActive) {
//do your work here
delay(1000)
}
}
}
//start the loop
val repeatFun = repeatRequest()
//Cancel the loop
repeatFun.cancel()

- 492
- 3
- 9
I recommended using SingleThread because you do not have to kill it after using. Also, "stop()" method is deprecated in Kotlin language.
private fun mDoThisJob(){
Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate({
//TODO: You can write your periodical job here..!
}, 1, 1, TimeUnit.SECONDS)
}
Moreover, you can use it for periodical job. 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.

- 134,786
- 31
- 255
- 325

- 6,204
- 45
- 38
-
You still have to kill it when you navigate away from whatever is using it, or you'll leak the references it is capturing. – Tenfour04 Apr 04 '23 at 12:48
I use the following function(s):
fun <T> delayedAsyncTask(delayMs: Long = 0, task: () -> T): ScheduledFuture<T> {
return Executors
.newSingleThreadScheduledExecutor()
.schedule(Callable<T> { task() }, delayMs, TimeUnit.MILLISECONDS)
}
fun <T> asyncTask(task: () -> T) = delayedAsyncTask(0, task)
Here's a unit test for the delayed function. Use of the returned future is optional of course.
@Test
fun `delayed task work correctly`() {
val future = delayedAsyncTask(1000) {
"lambda returns hello world"
}
assertEquals(false, future.isDone)
Thread.sleep(1100)
assertEquals(true, future.isDone)
assertEquals("lambda returns hello world", future.get())
}

- 21,643
- 8
- 63
- 62
Another way to create a redundant job other than this; that does not require the function to be suspend.
val repeatableJob = CoroutineScope(Dispatchers.IO).launch {
while (true) {
delay(1000)
}
}
Cancel when you are done -
repeatableJob.cancel()

- 1,535
- 3
- 16
- 29
-
Careful using an unmanaged CoroutineScope--this coroutine will leak memory and threads if not manually cancelled when the objects it captures references to become obsolete. It's the same issue GlobalScope has. [More info here](https://elizarov.medium.com/the-reason-to-avoid-globalscope-835337445abc) – Tenfour04 Apr 04 '23 at 12:46
-
I do have suggested cancelling task above and the article just suggests the same manual cancellation or using withContext with suspend function, either way its not a difference with one exception where withContext blocks failure will result in cancellation of all coroutines associated with it, [check this](https://stackoverflow.com/a/56866621/7873768) – MDT Apr 04 '23 at 14:08
-
Yes, you recommended cancelling the Job. I was just adding a point, since using `CoroutineScope().launch` is a common anti-pattern some newbies use to avoid the GlobalScope warning without understanding the warning and when it is appropriate to use GlobalScope. – Tenfour04 Apr 04 '23 at 14:22
-
fair point - there is no lifecycle owner in my way of creating coroutine. So yes manual clean up is mandatory. I do strictly use lifecycles events to cancel or recreate and also sometimes to manually cancel it and re-create when needed this way i have full control for adhoc scenarios. – MDT Apr 04 '23 at 16:26
if you are call function in UI.
Timer().schedule(1000) {
activity?.runOnUiThread {
doSomething()
}
}

- 793
- 7
- 8