How to set timer to call a function every n minutes?

19,234

Use following code to call your function every 15/30/45

 final Handler handler = new Handler();
Timer    timer = new Timer();
    TimerTask doAsynchronousTask = new TimerTask() {       
        @Override
        public void run() {
            handler.post(new Runnable() {
                @SuppressWarnings("unchecked")
                public void run() { 
                   try {
                        "Your function call  " 
                       }
                 catch (Exception e) {
                        // TODO Auto-generated catch block
                    }
                }
            });
        }
    };
    timer.schedule(doAsynchronousTask, 0, "Timer value"); 
Share:
19,234
Shweta
Author by

Shweta

Android Developer (Beginners level)

Updated on June 11, 2022

Comments

  • Shweta
    Shweta almost 2 years

    I want to set up a timer in an Android application that will call a function after every 15/30/45 and n minutes when user login. But also it will stop timer when user log off. and timer begin from start if user login again. I want that option(15/30/45/n miutes) to be saved in database so that I can update list after sync.

    Is Timer a good approach or I need to use alarm services? Or is there any system services required?

    Is it possible to change previous doc/file in local phone database storage to new doc that is receiving through web server? is there any system services required to do so?

    • class stacker
      class stacker about 11 years
      You want to use the AlarmManager for delays of this magnitude, with RTC or RTC_WAKEUP option, depending on your needs. Apart from that, it's hard to say what you mean by "user logs on/off". Either way, don't use Timer on Android, it's almost always the wrong way. No Service required because AlarmManager takes care of everything for you.
    • Nirmal
      Nirmal about 11 years
  • Mujeeb
    Mujeeb about 6 years
    "Timer value" in the last line needs to be replaced with an integer.
  • Taha alam
    Taha alam over 3 years
    use of countdown timer will be more memory efficient