Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use a TimerTask to run a thread?

I'm struggling to find documentation for the TimerTask function on Android. I need to run a thread at intervals using a TimerTask but have no idea how to go about this. Any advice or examples would be greatly appreciated.

like image 436
Alex Haycock Avatar asked Apr 05 '12 13:04

Alex Haycock


People also ask

Is TimerTask a thread?

TimerTask facilitates execution of one-time or recurring tasks using a Timer. TimerTask has really got nothing to do with Threads, apart from the fact that the Timer will execute these tasks in a background thread (though this could be considered an implementation detail of the Timer class).

How does TimerTask work in Java?

TimerTask is an abstract class defined in java. util package. TimerTask class defines a task that can be scheduled to run for just once or for repeated number of time. In order to define a TimerTask object, this class needs to be implemented and the run method need to be overridden.

Is Java Timer a thread?

Java Timer class is thread safe and multiple threads can share a single Timer object without need for external synchronization. Timer class uses java.


3 Answers

I have implemented something like this and it works fine:

    private Timer mTimer1;
    private TimerTask mTt1;
    private Handler mTimerHandler = new Handler();

    private void stopTimer(){
        if(mTimer1 != null){
            mTimer1.cancel();
            mTimer1.purge();
        }
    }

    private void startTimer(){
        mTimer1 = new Timer();
        mTt1 = new TimerTask() {
            public void run() {
                mTimerHandler.post(new Runnable() {
                    public void run(){
                        //TODO
                    }
                });
            }
        };

        mTimer1.schedule(mTt1, 1, 5000);
    }
like image 109
Alex Avatar answered Oct 04 '22 09:10

Alex


You use a Timer, and that automatically creates a new Thread for you when you schedule a TimerTask using any of the schedule-methods.

Example:

Timer t = new Timer();
t.schedule(myTimerTask, 1000L);

This creates a Timer running myTimerTask in a Thread belonging to that Timer once every second.

like image 26
Jave Avatar answered Oct 04 '22 11:10

Jave


This is perfect example for timer task.

Timer timerObj = new Timer();
TimerTask timerTaskObj = new TimerTask() {
    public void run() {
       //perform your action here
    }
};
timerObj.schedule(timerTaskObj, 0, 15000);
like image 11
Kalai Prakash Avatar answered Oct 04 '22 10:10

Kalai Prakash