David Elliott
David Elliott

Reputation: 113

Android Timer Tasks

I'm trying to make a timer that will do a certain thing after a certain amount of time:

 int delay = 1000; 

        int period = 1000; 

        Timer timer = new Timer();

        timer.scheduleAtFixedRate(new TimerTask() {

        public void run() {

            //Does stuff

        }
        }, delay, period);

However, the app crashes after the wait period. This is Java code, so it might not be entirely compatible with Android (like while loops). Is there something I'm doing wrong?

Upvotes: 0

Views: 101

Answers (2)

Jim
Jim

Reputation: 10278

If your app is crashing after the wait period, then your timer task is doing its job and executing your code on schedule. The problem must then be in your code where run() occurs (for example, you may be trying to update UI elements in a background thread).

If you post more code and your logcat, I can probably be more specific about the error you are getting, but your question was in regards to TimerTask.

Upvotes: 1

Anthony
Anthony

Reputation: 3074

Something like this should work, create a handler, and wait 1 second :) This is generally the best way of doing it, its the most tidy and also probably the best on memory too as its not really doing too much, plus as it's only doing it once it is the most simple solution.

Handler handler = new Handler(); 
handler.postDelayed(new Runnable() { 
   public void run() { 
   // do your stuff
   } 
}, 1000); 

If you would like something to run every one second then something like this would be best:

Thread thread = new Thread()
{
    @Override
    public void run() {
        try {
            while(true) {
                sleep(1000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
};
thread.start();

If you want a GUI thread then something like this should work:

    ActivityName.this.runOnUiThread(new Runnable()
    {
     public void run(){
 try {
            while(true) {
                sleep(1000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
     }
     });

Upvotes: 1

Related Questions