简体   繁体   中英

Why TimerTask is running twice?

I want to display a notification at a specific time for my android application. For example: at 3 pm print the notification message. I use this code:

private void checkNotificationStatus() {
     timer.schedule(new TimerTask() {
         @Override
         public void run() {
             addNotificationReminder();
         }
      }, new Date(appointment.getTimeInMillis()));
}

public void addNotificationReminder() {
   System.out.println("i'm here");
}

So, the timer works correctly but the message, "I'm here" is displayed twice instead of just once. If I put a long instead of a date as the second parameter in TimerTask (for example 2000), the message is printed just once. Nonetheless, if I put: appointment.getTimeInMillis() - System.currentTimeMillis() the message is printed twice again.

Any suggestion?

The checkNotificationStatus() is probably called two times. Maybe put a println() before timer.shedule() to check, whether the method is called multiple times or whether it really is the timers fault.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM