This article explores different ways to execute a function after an initial delay or periodically in Kotlin.

1. Using Timer class

The Timer class offers the facility for threads to schedule tasks for future execution in a background thread. For example, the println task is scheduled for one-time execution after a delay of 1 second below.

Download Code

 
The code can be further shortened as follows:

Download Code

 
Note that tasks may be scheduled for repeated execution at regular intervals. For example, the following code invokes the foo() function every 1 second.

Download Code

Output:

Running
Running


 
This can be further shortened as below:

Download Code

Output:

Running
Running


2. Using Executors class

Alternatively, we can get an executor that can schedule commands to run after a given initial delay or to execute periodically. For example, the following code calls the foo() function after a delay of 1 second using the schedule() function.

Download Code

 
To schedule a task to run periodically, use the scheduleAtFixedRate() function. For example, the following code invokes the foo() function every 1 second.

Download Code

Output:

Running
Running


3. Using Thread.sleep() function

Finally, we can use the Thread.sleep() function to temporarily cease execution of the current thread for the specified number of milliseconds.

Download Code

Output:

Start…
1 second elapsed…

That’s all about executing a function after an initial delay or periodically in Kotlin.