Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Restart Timer

I created a TimerTask with the following code:

    Screen_Timer_Task = new TimerTask() {

    @Override
    public void run() {

    runOnUiThread(new Runnable()
    {
            @Override
            public void run()
            {

                    // Do my stuff

            }
    });

    }

    };

Then, I start that TimerTask with that:

    Screen_Timer.scheduleAtFixedRate(Screen_Timer_Task, 1, 1);

This is working fine. But after calling

    Screen_Timer.cancel();

    Screen_Timer.purge();

it will not restart with

    Screen_Timer.scheduleAtFixedRate(Screen_Timer_Task, 1, 1);

The app is just crashing!!

like image 977
Jan Knoblauch Avatar asked Dec 06 '25 10:12

Jan Knoblauch


1 Answers

"The task may be run once " from docs timerTask

You must create TimerTask object again if you want to use it.

Also make Timer once again because cancel(): "Cancels the Timer and all scheduled tasks. If there is a currently running task it is not affected. No more tasks may be scheduled on this Timer. Subsequent calls do nothing."

like image 167
michal.luszczuk Avatar answered Dec 08 '25 00:12

michal.luszczuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!