Android run a Task Periodically-ThrowExceptions

Exception or error:

I want to run a method periodically in an android activity which updates a certain field after x seconds. I know it can be done in timerTask but what is the best way to do it? Code samples would be helpful.

How to solve:

You should use Handler and its postDelayed function. You can find example here: Repeat a task with a time delay?


You can use below android classes:


Handler handler=new Handler();
                handler.postDelayed(new Runnable() {
                    public void run() {

                  //your code


AlarmManager alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);

            // Set the alarm to start at approximately 2:00 p.m.
            Calendar calendar = Calendar.getInstance();

            Intent intent = new Intent(HomeActivity.this, Yourservice.class);
            alarmIntent = PendingIntent.getService(HomeActivity.this, 0, intent, 0);
            alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 600*1000, alarmIntent);


You can also do it by CountDownTimer

CountDownTimer countDownTimer;

 public void usingCountDownTimer() {
        countDownTimer = new CountDownTimer(Long.MAX_VALUE, 10000) {

            // This is called after every 10 sec interval. 
            public void onTick(long millisUntilFinished) {              
                setUi("Using count down timer");

            public void onFinish() {              

and onPause()

    protected void onPause() {
        try {
        } catch (Exception e) {


Leave a Reply

Your email address will not be published. Required fields are marked *