1. 程式人生 > >Android 定時迴圈執行任務

Android 定時迴圈執行任務

一個定時迴圈任務的工具,可以用於執行每隔固定時間就要執行一次的任務。例如大圖輪播,狀態監測什麼的。

共有4個Java檔案。具體的使用方法在最下面。

Counter.java

package com.***.android.time;
import java.util.HashMap;
/**
 * Created by zpybless on 2015/11/18.
 */
public class Counter{

    static class CountableState {

        int count;
}


    //單例模式
private static Counter counter
; public static Counter getInstance() { if (counter == null) { counter = new Counter(); } return counter; } private HashMap<ICountable, CountableState> states = new HashMap<ICountable, CountableState>(); //為每一個任務(使用同一個計時器)新增計數器,並啟動任務instance.onCountIncreasesToOne();
//同一個TickTimer,呼叫多次start()的情況,計數器會增加 public void increase(ICountable instance) { CountableState state = states.get(instance); if (state == null) { state = new CountableState(); state.count = 1; states.put(instance, state); instance.onCountIncreasesToOne(); } else
{ state.count++; } } //結束任務,計數器-1,如果是最後一個執行緒,就結束instance.onCountDecreasesToZero();; public void decrease(ICountable instance) { CountableState state = states.get(instance); state.count--; if (state.count == 0) { states.remove(instance); instance.onCountDecreasesToZero(); } } public int getCount(ICountable instance) { CountableState state = states.get(instance); return state == null ? 0 : state.count; } }

  ICountable.java
package com.***.android.time;
/**
 * Created by zpybless on 2015/11/18. */
public interface ICountable {
    void onCountIncreasesToOne();
    void onCountDecreasesToZero();
}
 

TickTimer.java

package com.***.android.time;
import android.os.Handler;
/**
 * 計時器
* Created by zpybless on 2015/11/18.
 */
public class TickTimer implements ICountable {

    /**
     * 計時器對外介面,每隔一段時間,執行某一任務     * @param duration 時間間隔
* @param runnable 任務程序
*/
public TickTimer(TimeSpan duration, Runnable runnable) {
        this.duration = duration;
        this.runnable = runnable;
}


    private static int nextSessionID;
    private int sessionID;
    private TimeSpan duration;
    private boolean isRunning;
    public boolean isRunning() {
        return isRunning;
}

    private Runnable runnable;
    private static Handler handler = new Handler();
    private Runnable onTickRunnable;
//同一個TickTimer物件,對此呼叫此方法,onCountIncreasesToOne()只會被執行1次(第一次)
public void start() {
        Counter.getInstance().increase(this);
}

    public void stop() {
        Counter.getInstance().decrease(this);
}

    private void onTick() {

        if (runnable != null) {
            runnable.run();
}
    }

    @Override
public void onCountIncreasesToOne() {

        sessionID = nextSessionID;
nextSessionID++;
onTickRunnable = new Runnable() {

            public int sessionID = TickTimer.this.sessionID;
            public void run() {
                onTick();
                if (isRunning && sessionID == TickTimer.this.sessionID) {
                    //再次執行本執行緒,使onTick()裡面的執行緒任務達到迴圈執行的效果
handler.postDelayed(onTickRunnable, duration.getMilliseconds());
}
            }
        };
//執行緒開關
isRunning = true;
//啟動執行緒
onTickRunnable.run();
}

    @Override
public void onCountDecreasesToZero() {
        isRunning = false;
}
}

TimeSpan.java

package com.***.android.time;
/**時間相關工具類
* Created by zpybless on 2015/11/18.
 */
public class TimeSpan {

    private long milliseconds;
    public long getMilliseconds() {
        return milliseconds;
}

    public TimeSpan(long milliseconds) {
        this.milliseconds = milliseconds;
}

    public int getMillisecondPart() {
        return (int)(milliseconds % 1000);
}

    public int getSecondPart() {
        return getSecond(milliseconds);
}

    public int getMinutePart() {
        return getMinute(milliseconds);
}

    public int getHourPart() {
        return getHour(milliseconds);
}

    @Override
public String toString() {
        return getClockHmsString(milliseconds);
}


    public static String getClockHmsString(long milliseconds) {
        return String.format("%d:%02d:%02d", getHour(milliseconds), getMinute(milliseconds), getSecond(milliseconds));
}

    public static String getCounterHmsString(long milliseconds) {
        return String.format("%02d:%02d:%02d", getHour(milliseconds), getMinute(milliseconds), getSecond(milliseconds));
}

    private static int getHour(long milliseconds) {
        return (int)(Math.floor((float)milliseconds / (1000 * 60 * 60)));
}

    private static int getMinute(long milliseconds) {
        return (int)(Math.floor((float)milliseconds / (1000 * 60))) % 60;
}

    private static int getSecond(long milliseconds) {
        return (int)(Math.floor((float)milliseconds / 1000)) % 60;
}


    public static TimeSpan fromMilliseconds(float time) {
        return new TimeSpan((long)time);
}

    public static TimeSpan fromSeconds(float time) {
        return new TimeSpan((long)(time * 1000));
}

    public static TimeSpan fromMinutes(float time) {
        return new TimeSpan((long)(time * 1000 * 60));
}

    public static TimeSpan fromHours(float time) {
        return new TimeSpan((long)(time * 1000 * 60 * 60));
}

    public static TimeSpan fromDays(float time) {
        return new TimeSpan((long)(time * 1000 * 60 * 60 * 24));
}
}

具體使用:

TickTimer timer = new TickTimer(TimeSpan.fromSeconds(10.00f)【時間間隔】, new Runnable() {
@Overridepublic void run() { //要執行的任務}});timer.start();

相關推薦

Android 定時迴圈執行任務

一個定時迴圈任務的工具,可以用於執行每隔固定時間就要執行一次的任務。例如大圖輪播,狀態監測什麼的。 共有4個Java檔案。具體的使用方法在最下面。 Counter.java package com.***.android.time; import java.util.H

定時AlarmManager迴圈執行後臺任務和多個定時迴圈後臺任務寫在一起

定時迴圈執行某些任務,在開發中是很常見的一種方式,Android中有兩種定時器可以實現,一種是Alarm,另一種是AlarmManager,Alarm在Android4.4以後,這種方式的定時器不太準確,Android官方為了優化手機電池使用時間,將多個差不多時

linux進程管理-定時定期執行任務

dai clas XA 自動 c99 post 定時執行 shell 文件 0.計劃任務的命令:   at  安排作業在某一時刻執行    batch  安排作業在系統負載不重時執行    crontab 安排周期性運行的作業    1.at命令用法:

spring註解 @Scheduled(cron = "0 0 1 * * *")實現定時執行任務

  @Scheduled(cron = "0 0 1 * * *")    在使用該註解以前請做好以下準備工作,配置好相應的xm檔案。   配置定時註解的步驟:http://blog

定時執行任務

java定時器 現象: 瞭解java定時器:schedule方法和scheduleAtFixedRate方法 定時器 區別一: schedule方法,定時任務,按照程式碼實際執行任務的時間進行固定頻率

【js】用js定時迴圈執行語句和定時延緩執行

        最近在專案中,需要使用到站內信的訊息推送方式在網站中給使用者推送訊息,就是在頁面有下角推送一個彈窗,這裡需要我們定時去後臺查詢是否有訊息推送過來,所以需要在JS層面進行定時執行查詢的任務。 這裡用到了JS的兩個函式方法,一個是setInterval,一個是setT

spring註解 @Scheduled(cron = "0 0 1 * * *")的使用來實現定時執行任務

<span style="font-size:14px;">初次接觸定時類的小程式,還是走了很多的彎路,如今終於搞定了,總結如下:</span><span style="font-size:14px;">import com.activi

學習如何每隔一段時間定時重複執行任務

學習了定時執行任務功能。並寫了個demo學習研究下。 參考blog: 1. 通過Service和BroadcastReceiver實現 寫一個Service執行定時發廣播操作 public class AlarmService extends Service {

Animation插值器:解決Android Animation 迴圈執行的停頓問題

在Android開發中,有時候我們需要一個動畫一直迴圈執行下去,常見的如laoding菊花一直旋轉,這時候就需要使用Animation的repeat功能,如下: animation = new RotateAnimation(0f, 360f, lightView.getW

Android ScheduledExecutorService 週期性執行任務

1.需求:     我的頁面上有個按鈕預設顯示的文字 one     如果當前時間為 9:00 時 按鈕的文字不改變     但當時間到9:20時 需要將按鈕的文字改變為 two 2.思路:    需

Android執行定時迴圈任務

一. 採用Handler的postDelayed(Runnable, long)方法(最簡單的android實現) 二. 採用Handler與timer及TimerTask結合的方法(比較多的任務時建議使用) 下面逐個介紹: 第一種方法: 採用Han

android 使用Handler.postDelayed方法實現迴圈執行定時任務

1,首先建立一個Handler物件   Handler handler=new Handler();   2,然後建立一個Runnable對 Runnable runnable=new Run

spring配置quartz定時任務,支援初始化執行迴圈執行,定點執行

Spring配置quartz的方式有註解的方式和配置檔案的方式,今天主要說使用配置檔案的方式來實現初始化執行和定點執行 第一步,在pom.xml配置jar包依賴 <!-- 新加quartz依賴 --> <dependency>

使用AlarmManager實現Android應用每天定時執行任務

介紹 android官方文件:AlarmManager 在Android平臺,除了使用AlarmManger外,還可以使用Timer或者Handler來實現定時任務,但這兩種方式定時並不會太準確;因此如果我們需要實現精準定時任務,使用AlarmManger更

Android利用AlarmManager執行定時任務

Android中的AlarmManager功能很強大,它是一個全域性定時器,可以在指定時間或者指定週期啟動其他元件(包括Activity、Service、BroadcastReceiver)。 使用AlarmManager程式設計也很簡單,只要按照以下步驟即可: 1.獲取A

android使用AlarmManager實現應用每天定時執行任務

簡介: 關於service 大家應都知道是Android 四大元件之一,用來執行後臺任務的。 Android 中的定時任務一般有兩種實現方式,一種是使用Java API 裡提供的Timer 類,一種是使用Android 的Alarm 機制。 那麼首先我們來

每天00:00:01迴圈執行定時任務

package net.spring.utils; import java.text.ParseException; import java.util.Calendar; import java.u

Android Gradle 自定義任務執行命令行

andro blog tasks type mman 執行 adl col command tasks.create("name": "testAssemble", "type": Exec) { workingDir "../" commandLin

java中定時執行任務

views sch start bsp tails pri ted java file 現在項目中用到需要定時去檢查文件是否更新的功能。timer正好用於此處。 用法很簡單,new一個timer,然後寫一個timertask的子類即可。 代碼如下: [java] vie

java Timer 定時每天淩晨0點執行任務

nth 任務 定時任務 執行 auth oid ddd imp java import java.util.TimerTask; /** * 執行內容 * @author admin_Hzw * */ public class Task exten