Android 定时循环执行任务

本文介绍了一个用于定时循环执行任务的工具,适用于大图轮播、状态监测等场景。主要包括Counter、TickTimer和TimeSpan三个Java文件,详细使用方法在文章底部给出。
摘要由CSDN通过智能技术生成

一个定时循环任务的工具,可以用于执行每隔固定时间就要执行一次的任务。例如大图轮播,状态监测什么的。

共有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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值