Handler Timer TimerTask ScheduledExecutor 循環任務解析

使用Handler執行循環任務java

private Handler handler = new Handler();
private int mDelayTime = 1000;
private Runnable runnable = new Runnable() {
    @Override
    public void run() {
        if (mDelayTime > 0) {
            Log.d(TAG, "run::time=" + mDelayTime);
            handler.postDelayed(runnable, mDelayTime);
            mDelayTime--;
        }
    }
};
handler.postDelayed(runnable, 1000);

Handler能夠重複執行某個任務;Timer若在取消執行某個任務後,再次執行時會拋出IllegalStateException異常.須要再次建立一個Timer對象.安全

Handler能夠調整循環執行的週期;而Timer須要消耗較大資源才能作到.併發

UI更新時,在建立Handler時能夠指定所在的線程,通常在主線程中建立,更容易更新UI.ide

Handler的內存佔比更低.工具

使用Timer和TimerTask執行定時或者循環任務post

特定:當啓動和取消任務時,可控制任務的執行;spa

第一次執行任務時,能夠指定延遲時間;線程

Timer類用於任務的調度,TimerTask中的run()實現具體的任務;對象

Timer實例能夠調度多任務,且是線程安全的;blog

Timer在構造時,建立了一個工做線程(子線程),該線程用於執行具體任務;

import java.util.TimerTask;
public class Task2 {
  public static void main(String[] args) {
    TimerTask task = new TimerTask() {
      @Override
      public void run() {
        System.out.println("Hello !!!");
      }
    };
    Timer timer = new Timer();
    long delay = 0;
    long intevalPeriod = 1 * 1000;
    // schedules the task to be run in an interval
    timer.scheduleAtFixedRate(task, delay,intevalPeriod);
  } // end of main
} 

ScheduledExecutorService執行定時或循環任務

ScheduledExecutorService類做爲併發工具類被引入,是最理想的定時任務實現方式;

相比於Timer的單線程,上述方法經過線程池的方式來執行任務;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Task3 {
  public static void main(String[] args) {
    Runnable runnable = new Runnable() {
      public void run() {
        System.out.println("Hello !!");
      }
    };
    ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS);
  }
} 
相關文章
相關標籤/搜索