Android run a Task Periodically

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() {              
                start();
            }
        }.start();
    }

and onPause()

@Override
    protected void onPause() {
        super.onPause();
        try {
            countDownTimer.cancel();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

You can use below android classes:

1.Handler

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

                  //your code
                   handler.postDelayed(this,20000); 
                    }
                },20000);

2.AlarmManager

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


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

            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 should use Handler and its postDelayed function. You can find example here: Repeat a task with a time delay?