Sunny
Sunny

Reputation: 68

Timer task stop calling run method after first run

I am new to programming and I am doing one android application on which I have one requirement where I need to monitor some logs for the 30s. I am using a timer task but what is happening, if the 30s are over and the run method executed once it is terminated the timer task not repeating.

Here is my code:

connectivityTimerTask = new ConnectivityTimerTask();
timer = new Timer(true);
//timer = new Timer(); // tried with this but it is not working
timer.schedule(connectivityTimerTask,30 * 1000);

TimerTask:

public class ConnectivityTimerTask extends TimerTask {

        @Override
        public void run() {
            Log.error("----- ACK NotReceived -----" + System.currentTimeMillis());
            //resetMonitor(); using this method I am setting the timer again
        }
    }

I want to know what's the best practice for scheduling repeating time. Am I using the correct way? Can I use the resetMonitor() method?

Upvotes: 0

Views: 787

Answers (3)

Cole Tustin
Cole Tustin

Reputation: 111

To repeatedly run some code after a set period of time, use a Runnable with a Handler like so

Handler handler = new Handler();

Runnable runnable = new Runnable() {
    @Override
    public void run() {
        // do your logging
        handler.postDelayed(this, 30000);
    }
};

 handler.post(runnable); // or handler.postDelayed(runnable, 30000) if you want it to wait 30s before starting initially

To cancel

handler.removeCallbacks(runnable);

Upvotes: 1

Zain
Zain

Reputation: 40908

Instead of of schedule(), You can use Timer task that can be scheduled at fixed rate with scheduleAtFixedRate,

int THIRTY_SECONDS = 30 * 1000;
Timer mTimer = new Timer();
mTimer.scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
        // do whatever you want every 30s
        Log.e("TAG", "----- ACK NotReceived -----" + System.currentTimeMillis());
    }
}, 0, THIRTY_SECONDS);

Whenever you want to stop the timer call timer.cancel()

Upvotes: 2

Mahima MS
Mahima MS

Reputation: 153

The line

timer.schedule(connectivityTimerTask,30 * 1000)

runs your task after a 30s delay and once the task completes, the timer's job is done.

If you want to keep running your task at periodic intervals, you have to also specify an interval period

schedule (TimerTask task, long delay, long period) // "period" specifies how often you want to run the task

Read the documentation here.

Upvotes: 1

Related Questions