您的位置:首页 > 其它

一个简陋的自定义用线程Thread实现的计时器Timer,可以增加定时时间

2017-03-03 17:06 381 查看
原来用的Timer(java.util.Timer),后来需要中途增加延迟时间,Timer不支持。自己写了个简陋的,应该够用。

类如下:

public class ExTimer extends Thread {
private String TAG = "ExTimer";
private CallBack callBack;

/**
* 任务开始的时间
*/
private long startTime;
/**
* 延迟多久执行
*/
private long delay;
/**
* 判断这个线程是否还执行回调
*/
private boolean stillRun = true;

private ExTimer newTask;

public ExTimer() {

}

@Override
public void run() {
try {
startTime = System.currentTimeMillis();
Thread.sleep(delay);
if (stillRun) {
callBack.run();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}

/**
* 模仿Timer的使用方法,因为之前用的是Timer
* @param callBack
* @param delay
*/
public void schedule(CallBack callBack, long delay) {
this.callBack = callBack;
this.delay = delay;
start();
}

/**
* 增加延迟时间
* @param addDelay
*/
public void addDelay(long addDelay) {

//计算这个计时器原来已经走了多久
long cha = System.currentTimeMillis() - startTime;

//计算这个计时器原来剩下的时间
long lastDelay = this.delay - cha;

if (lastDelay > 0) {
//新的计时器延迟时间,剩下的+新增的
this.delay = lastDelay + addDelay;
if (newTask != null) {
newTask.interrupt();
}
newTask = new ExTimer();
newTask.schedule(callBack, delay);
startTime = System.currentTimeMillis();
stillRun = false;
}
}

/**
* 取消计时器
*/
public void cancel() {
if (newTask!=null){
newTask.interrupt();
newTask = null;
}
stillRun = false;
interrupt();
}

/**
* 提供个接口回调
*/
interface CallBack {
void run();
}
}


使用方法

创建,并定义一个任务,3秒后执行

ExTimer t = new ExTimer();
t.schedule(new ExTimer.CallBack() {
@Override
public void run() {
Log.i(TAG, "run: dely");
}
},3000);


增加5秒的延迟时间,相当于原来的任务是延迟8秒执行:

if (t!=null){
t.addDelay(5000);
}


取消任务,不再执行:

if (t!=null){
t.cancel();
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  线程 Timer Thread
相关文章推荐