Summary and examples of four ways to implement timer in Android

Keywords: Android Java

android Four ways to realize timer in

The first way to use Timer and TimerTask

1. Inheritance relationship


Basic methods


For example:

timer.schedule(task, delay,period);  
//Delay is long,period is long: after delay milliseconds from now on, it is executed every period milliseconds.

The schedule method has three parameters

The first parameter is the object of TimerTask type. Our implementation of the run() method of TimerTask is a task to be executed periodically;

The second parameter has two types. The first is long, which indicates how long it will take to start execution. The other is Date, which indicates when it will start execution;

The third parameter is the execution cycle, which is of type long.


TimerTask task= new TimerTask() { 
     public void run() { 
        Log.i("MainActivity",count + ""); 

//Here are several ways to schedule task s:

//Time is of Date type: executed once at the specified time.  
timer.schedule(task, time);  
//firstTime is of Date type and period is long, which means that it is executed every period millisecond from the first time.  
timer.schedule(task, firstTime,period);    
//Delay is of long type: it is executed once in delay milliseconds from now on.  
timer.schedule(task, delay);   
//Delay is long,period is long: after delay milliseconds from now on, it is executed every period milliseconds.  
timer.schedule(task, delay,period);  

Note: the task should be cancelled in ondestore(), otherwise it may crash

3. An APP that uses TimerTask to perform certain operations on a regular basis. Even if it exits, it will still run for a while in TimerTask, but it cannot run for a long time

The second way is to use CountDownTimer


CountDownTimer cdt = new CountDownTimer(10000, 100) { 
  public void onTick(long millisUntilFinished) { 
    tv_hello.setText(millisUntilFinished + ""); 
  public void onFinish() { 

2. The example above is

Execute methods in onTick every 100 milliseconds
Until 10000 / 100 times of execution, the method in onFinish() will be executed finally

The third way is AlarmManager


Intent intent2 = newIntent(ReadLogService.this,TestBroadcast.class); 
PendingIntent pd =PendingIntent.getBroadcast(getApplicationContext(), 0, intent2,PendingIntent.FLAG_ONE_SHOT); 
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE); 
long triggerTime =SystemClock.elapsedRealtime() + 5*1000; 
am.set(AlarmManager.ELAPSED_REALTIME,triggerTime, pd); 

The fourth method, AlarmManager

handler.sendEmptyMessageDelayed(0, 4000);//Start the handler to implement the 4-second periodic execution 
private Handler handler = new Handler(){ 
public voidhandleMessage(android.os.Message msg) { 
          //Logical processing 
            handler.sendEmptyMessageDelayed(0,4000);//Execute again in 4 seconds 

Posted by dionyssos on Mon, 04 May 2020 14:52:10 -0700