How do i call a function after a delay in Kotlin

Published September 02, 2022

In this kotlin example we will cover call a function after a delay. Using Java Timer class we will pause method call after some delay by shedule() method.

Here is the example 

package com.example.kotlinexamples
import java.util.Timer
import kotlin.concurrent.schedule
fun main(args: Array<String>) {

    // Execution starting point
    println("Hello world!!")

    // Delay of 5 sec
    Timer().schedule(3000){

        //calling a function
        methodCallWithDelay()
    }
}

fun methodCallWithDelay(){
    println("Method called after delay")
}

 

After execute this file first it will print  and after 3 seconds will execute  methodCallWithDelay() and print "Method called after delay"

 

Output: 

Hello world!!
Method called after delay

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

323 Views