Android
Timer
Android App Development
Tutorial
How-to Guide

How to set timer in android?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

There is no single timer API that is correct for every Android use case. A countdown shown on screen, a short UI delay, and work that must happen later in the background are three different problems and should be solved with different tools.

That is why the real question is not just "how do I set a timer," but "what kind of timed behavior do I need?" Once that is clear, the right API becomes much easier to choose.

Use CountDownTimer for Visible Countdowns

If the user should see a ticking countdown, CountDownTimer is the simplest built-in choice:

kotlin
1import android.os.Bundle
2import android.os.CountDownTimer
3import android.widget.TextView
4import androidx.appcompat.app.AppCompatActivity
5
6class MainActivity : AppCompatActivity() {
7    private var timer: CountDownTimer? = null
8
9    override fun onCreate(savedInstanceState: Bundle?) {
10        super.onCreate(savedInstanceState)
11        setContentView(R.layout.activity_main)
12
13        val countdownText = findViewById<TextView>(R.id.countdownText)
14
15        timer = object : CountDownTimer(10_000, 1_000) {
16            override fun onTick(millisUntilFinished: Long) {
17                countdownText.text = "Seconds left: ${millisUntilFinished / 1000}"
18            }
19
20            override fun onFinish() {
21                countdownText.text = "Done"
22            }
23        }.start()
24    }
25
26    override fun onDestroy() {
27        timer?.cancel()
28        super.onDestroy()
29    }
30}

This fits quiz timers, resend-code countdowns, and other user-visible countdown UI.

Use a Delayed Callback for One-Shot UI Work

If you only need to run something once after a short delay on the main thread, a delayed callback is often enough:

kotlin
1import android.os.Bundle
2import android.os.Handler
3import android.os.Looper
4import androidx.appcompat.app.AppCompatActivity
5
6class SplashActivity : AppCompatActivity() {
7    private val handler = Handler(Looper.getMainLooper())
8    private val navigateTask = Runnable {
9        // navigate to the next screen
10    }
11
12    override fun onCreate(savedInstanceState: Bundle?) {
13        super.onCreate(savedInstanceState)
14        handler.postDelayed(navigateTask, 2_000)
15    }
16
17    override fun onDestroy() {
18        handler.removeCallbacks(navigateTask)
19        super.onDestroy()
20    }
21}

This is a better fit than older Java TimerTask code for most UI delays because it is explicitly tied to the main thread.

Coroutines Are Often the Cleanest Modern Choice

If your project already uses Kotlin coroutines, a lifecycle-aware coroutine is usually the cleanest way to express a delay:

kotlin
1import androidx.lifecycle.lifecycleScope
2import kotlinx.coroutines.delay
3import kotlinx.coroutines.launch
4
5lifecycleScope.launch {
6    delay(2_000)
7    // update UI or navigate
8}

This reads well, integrates naturally with modern Android architecture, and avoids some of the callback clutter that grows around handlers in larger screens.

Do Not Use UI Timers for Background Scheduling

If the task must happen later even when the app is not on screen, UI timers are the wrong tool. For background work, the better choices are:

  • 'WorkManager for deferrable background jobs'
  • 'AlarmManager for cases that truly need alarm-style scheduling'

Trying to keep an Activity timer alive in the background is unreliable because Android is free to stop or destroy the process.

Choose the Timer by Behavior, Not by Familiarity

A practical rule is:

  • choose CountDownTimer for countdown displays
  • choose Handler.postDelayed for short one-shot UI delays
  • choose coroutines when the app already uses them
  • choose WorkManager or AlarmManager for delayed background behavior

The old instinct to reach for Timer or TimerTask everywhere usually leads to code that is harder to tie back to the Android lifecycle.

Common Pitfalls

The biggest mistake is starting a timer in an Activity or Fragment and forgetting to cancel it. That can leak work or try to update views that no longer exist.

Another common problem is using a UI timer for background scheduling. What works on a foreground test device often fails once the app is backgrounded or the process is reclaimed.

People also update views from the wrong thread when they use older timer APIs. Anything touching the UI should be on the main thread.

Finally, do not overcomplicate simple delays. If you only need one delayed action, a small delayed callback or coroutine is usually clearer than a repeating timer abstraction.

Summary

  • Use CountDownTimer for visible countdowns.
  • Use a delayed callback or coroutine for short UI delays.
  • Use WorkManager or AlarmManager for background timing needs.
  • Cancel timers when the owning lifecycle ends.
  • Pick the timer API based on the behavior you need, not on habit.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.