Take the 2-minute tour ×

First of all, I could not even chose the method to use, i'm reading for hours now and someone says use 'Handlers', someone says use 'Timer'. Here's what I try to achieve:

At preferences, theres a setting(checkbox) which to enable / disable the repeating job. As that checkbox is checked, the timer should start to work and the thread should be executed every x seconds. As checkbox is unchecked, timer should stop.

Here's my code:

Checking whether if checkbox is checked or not, if checked 'refreshAllServers' void will be executed which does the job with timer.

boolean CheckboxPreference = prefs.getBoolean("checkboxPref", true);
                if(CheckboxPreference == true) {
                    Main main = new Main();
                } else {
                    Main main = new Main();

The refreshAllServers void that does the timer job:

public void refreshAllServers(String start) {

    if(start == "start") {

        // Start the timer which will repeatingly execute the thread

    } else {

        // stop the timer


And here's how I execute my thread: (Works well without timer)

Thread myThread = new MyThread(-5);

What I tried?

I tried any example I could see from Google (handlers, timer) none of them worked, I managed to start the timer once but stoping it did not work. The simpliest & understandable code I saw in my research was this:

new java.util.Timer().schedule( 
        new java.util.TimerTask() {
            public void run() {
                // your code here
share|improve this question
See if the answer here helps. –  yorkw Jul 24 '12 at 21:26

4 Answers 4

up vote 12 down vote accepted

Just simply use below snippet

private Handler handler = new Handler();

private Runnable runnable = new Runnable() 

    public void run() 
         // Do the stuff

         handler.postDelayed(this, 1000);

To stop it use


Should do the trick.

share|improve this answer
Your solution worked well too, as i found some other solution. –  sarkolata Jul 25 '12 at 17:52
I think this the best solution. –  Code Droid Jul 25 '12 at 21:17
what if the user wants to accomplish something that uses connection to internet ? applying the above will make the handler and the runnable run on the UI thread, which prevents doing any network things. You need to implement thread there. –  tony9099 Sep 23 '13 at 19:23
Than add tread or asynctask to //Do the stuff part –  Tuna Karakasoglu Sep 24 '13 at 6:46
This is clever and I've used it in one part of my program and it works fine. But then I tried to use is in a service-like part of my program that does not have any UI, and that results in "java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()", which is fair enough. So this is a neat way to do timer-like processing, but just not in parts of the app that don't have a UI. –  RenniePet Sep 6 at 8:15

I would think to use AlarmManager http://developer.android.com/reference/android/app/AlarmManager.html

If checkbox is on call method where

AlarmManager alarmManager = (AlarmManager)SecureDocApplication.getContext()
PendingIntent myService = PendingIntent.getService(context, 0, 
                new Intent(context, MyService.class), 0);

long triggerAtTime = 1000;
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, triggerAtTime, 5000 /* 5 sec*/, 

If checkbox is off cancel alarm manager

share|improve this answer
And which is the part that i will insert my code? –  sarkolata Jul 25 '12 at 15:15
Have a class member variable which is instance of alarm manager. When checkbox is on call a method with that code. when off call method to shut down alarm manager. It it's going to happen when user browses through activities, then in inherited Application class. If user can exit app and that still need to be running then in the service. –  Maxim Jul 25 '12 at 15:27

Use a CountDownTimer. The way it works is it will call a method on each tick of the timer, and another method when the timer ends. At which point you can restart if needed. Also I think you should probably be kicking off AsyncTask rather than threads. Please don't try to manage your own threads in Android. Try as below. Its runs like a clock.

 CountDownTimer myCountdownTimer =    new CountDownTimer(30000, 1000) {

 public void onTick(long millisUntilFinished) {
     // Kick off your AsyncTask here.

 public void onFinish() {
     // the 30 seconds is up now so do make any checks you need here.
share|improve this answer
This does not repeatly does the thing. It did once then stopped! –  sarkolata Jul 25 '12 at 13:13
Yes it does not run indefinitely. If you want to run it indefinitely you could consider a background service. On the other hand there is nothing to prevent you from restarting the countdown timer if conditions are right, or from setting a longer duration. –  Code Droid Jul 25 '12 at 21:13

Thanks to everyone, I fixed this issue with using Timer.

             timer = new Timer();
                        new java.util.TimerTask() {
                            public void run() {
                                for(int i = 0; i < server_amount; i++) {
                                      servers[i] = "Updating...";                                     handler.sendEmptyMessage(0);
                                      new MyThread(i);

                    2000, 5000
share|improve this answer
Please state the advantages of this solution over the others. I'm not seeing it. –  Code Droid Jul 25 '12 at 21:15
No advantages, i just found out that Coders Paradise's answer is also working after i got mine working. –  sarkolata Jul 25 '12 at 21:30

Your Answer


