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

As I have seen it, java.util.Timer is the most used for implementing a timer.

For a repeating task:

new Timer().scheduleAtFixedRate(task, after, interval);

For a single run of a task:

new Timer().schedule(task, after);

task being the method to be executed
after the time to initial execution
(interval the time for repeating the execution)


I hope this one is helpful and may take less efforts to implement, Android CountDownTimer class


 new CountDownTimer(30000, 1000) {
      public void onTick(long millisUntilFinished) {
          mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);

      public void onFinish() {

Probably Timerconcept

new CountDownTimer(40000, 1000) { //40000 milli seconds is total time, 1000 milli seconds is time interval

 public void onTick(long millisUntilFinished) {
  public void onFinish() {


Method 2 ::

Program the timer

Add a new variable of int named time. Set it to 0. Add the following code to onCreate function in

//Declare the timer
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {

    public void run() {
        //Called each time when 1000 milliseconds (1 second) (the period parameter)

//Set how long before to start calling the TimerTask (in milliseconds)
//Set the amount of time between each execution (in milliseconds)

Go into the run method and add the following code.

//We must use this function in order to change the text view text
runOnUiThread(new Runnable() {

    public void run() {
        TextView tv = (TextView) findViewById(;
        time += 1;


It is situational.

The Android documentation suggests that you should use AlarmManager to register an Intent that will fire at the specified time if your application may not be running.

Otherwise, you should use Handler.

Note: The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running. For normal timing operations (ticks, timeouts, etc) it is easier and much more efficient to use Handler.


Here we go.. We will need two classes. I am posting a code which changes mobile audio profile after each 5 seconds (5000 mili seconds) ...

Our 1st Class

public class ChangeProfileActivityMain extends Activity {

    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub

        Timer timer = new Timer();
        TimerTask updateProfile = new CustomTimerTask(ChangeProfileActivityMain.this);
        timer.scheduleAtFixedRate(updateProfile, 0, 5000);


Our 2nd Class

public class CustomTimerTask extends TimerTask {

    private AudioManager audioManager;
    private Context context;
    private Handler mHandler = new Handler();

    // Write Custom Constructor to pass Context
    public CustomTimerTask(Context con) {
        this.context = con;

    public void run() {
        // TODO Auto-generated method stub

        // your code starts here.
        // I have used Thread and Handler as we can not show Toast without starting new thread when we are inside a thread.
        // As TimePicker has run() thread running., So We must show Toast through in a new Thread. Thats how it works in Android..
        new Thread(new Runnable() {
            public void run() {
                audioManager = (AudioManager) context.getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
       Runnable() {
                    public void run() {
                        if(audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT) {
                            Toast.makeText(context, "Ringer Mode set to Normal", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(context, "Ringer Mode set to Silent", Toast.LENGTH_SHORT).show();



Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]