How to set a timer in android


What is the proper way to set a timer in android in order to kick off a task (a function that I create which does not change the UI)? Use this the Java way:

Or there is a better way in android (android's handler)?

11/16/2015 4:28:31 PM

Accepted Answer

Standard Java way to use timers via java.util.Timer and java.util.TimerTask works fine in Android, but you should be aware that this method creates a new thread.

You may consider using the very convenient Handler class (android.os.Handler) and send messages to the handler via sendMessageAtTime(android.os.Message, long) or sendMessageDelayed(android.os.Message, long). Once you receive a message, you can run desired tasks. Second option would be to create a Runnable object and schedule it via Handler's functions postAtTime(java.lang.Runnable, long) or postDelayed(java.lang.Runnable, long).

11/21/2016 2:44:14 AM

yes java's timer can be used, but as the question asks for better way (for mobile). Which is explained Here.

For the sake of StackOverflow:

Since Timer creates a new thread it may be considered heavy,

if all you need is to get is a call back while the activity is running a Handler can be used in conjunction with a


private final int interval = 1000; // 1 Second
private Handler handler = new Handler();
private Runnable runnable = new Runnable(){
    public void run() {
        Toast.makeText(MyActivity.this, "C'Mom no hands!", Toast.LENGTH_SHORT).show();
handler.postAtTime(runnable, System.currentTimeMillis()+interval);
handler.postDelayed(runnable, interval);

or a Message

private final int EVENT1 = 1; 
private Handler handler = new Handler() {
    public void handleMessage(Message msg) {
        switch (msg.what) {         
        case Event1:
            Toast.makeText(MyActivity.this, "Event 1", Toast.LENGTH_SHORT).show();

            Toast.makeText(MyActivity.this, "Unhandled", Toast.LENGTH_SHORT).show();


Message msg = handler.obtainMessage(EVENT1);
handler.sendMessageAtTime(msg, System.currentTimeMillis()+interval);
handler.sendMessageDelayed(msg, interval);

on a side note this approach can be used, if you want to run a piece of code in the UI thread from an another thread.

if you need to get a call back even if your activity is not running then, you can use an AlarmManager

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow