Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android timer fires only once

Tags:

android

timer

I have this code where I want to try to send an e-mail report every hour (in the example to every second). If there is no coverage, try again within an hour etc. Somehow I managed to break the timer in sendUnsendedReports(): it fires only once. If I remove the call to sendUnsendedReports() than the timer is working perfectly. Even with the try-catch block around it, the timer only fires once. Please advice.

private void createAndScheduleSendReport() {
        delayedSendTimer = new Timer();
        delayedSendTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                Log.w("UrenRegistratie", "Try to send e-mail...");
                try{
                  sendUnsendedReports();
                }
                catch(Exception e){
                    // added try catch block to be sure of uninterupted execution
                }
                Log.w("UrenRegistratie", "Mail scheduler goes to sleep.");
            }
        }, 0, 1000);
    }
like image 307
Harmen Avatar asked Oct 26 '25 13:10

Harmen


2 Answers

It seems that sometimes timer doesn't works well as it should be. The alternative of this is use of Handler instead TimerTask.

You can use it like :

private Handler handler = new Handler();
handler.postDelayed(runnable, 1000);

private Runnable runnable = new Runnable() {
   @Override
   public void run() {
      try{
              sendUnsendedReports();
            }
            catch(Exception e){
                // added try catch block to be sure of uninterupted execution
            }
      /* and here comes the "trick" */
      handler.postDelayed(this, 1000);
   }
};

Check out this link for more detail. :)

like image 80
Ravi Bhatt Avatar answered Oct 28 '25 03:10

Ravi Bhatt


schedule() can be called in various ways, depending on if you want the task to execute once, or periodically.

To execute the task only once:

timer.schedule(new TimerTask() {
    @Override
    public void run() {
    }
}, 3000);

To execute the task every second after 3 s.

timer.schedule(new TimerTask() {
    @Override
    public void run() {
    }
}, 3000, 1000);

More example usages can be found in the method headers

public void schedule(TimerTask task, Date when) {
    // ...
}

public void schedule(TimerTask task, long delay) {
    // ...
}

public void schedule(TimerTask task, long delay, long period) {
    // ...
}

public void schedule(TimerTask task, Date when, long period) {
    // ...
}
like image 29
voghDev Avatar answered Oct 28 '25 02:10

voghDev