由於timer類實現的定時器是多線程的,這容易造成錯誤。所以實現了個單線程的定時器,雖然有點誤差。
1、任務執行接口
package TimerManager;
public interface ICmd {
public void excute();
}
2、任務基類
package TimerManager;
public class TaskCmd implements ICmd{
protected long excuteTime;
protected int times;
public TaskCmd(int delay, int times){
this.excuteTime = delay * 1000 + System.currentTimeMillis();
this.times = times;
}
@Override
public void excute() {
}
}
3、時間管理類:
package TimerManager;
import java.util.ArrayList;
public class TimerManager {
private static ArrayList<TaskCmd> taskList = new ArrayList<TaskCmd>();
private static ArrayList<TaskCmd> delList = new ArrayList<TaskCmd>();
public static void addTask(TaskCmd task){
taskList.add(task);
}
public static void loop(){
for(TaskCmd task : delList){
taskList.remove(task);
}
long nTime = System.currentTimeMillis();
for(TaskCmd task : taskList){
if(task.excuteTime <= nTime){
task.excute();
--task.times;
if(task.times <= 0)
delList.add(task);
}
}
}
}
4、任務類
package test;
import TimerManager.*;
public class testTask extends TaskCmd{
<span style="white-space:pre"> </span>public testTask(int delay, int times) {
<span style="white-space:pre"> </span>super(delay, times);
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>@Override
<span style="white-space:pre"> </span>public void excute() {
<span style="white-space:pre"> </span>System.out.println("111");
<span style="white-space:pre"> </span>}
}
5、mian函數循環
package test;
import TimerManager.*;
public class test {
<span style="white-space:pre"> </span>public static void main(String[] args) {
<span style="white-space:pre"> </span>TimerManager.addTask(new testTask(10,1));
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>while(true){
<span style="white-space:pre"> </span>try {
<span style="white-space:pre"> </span>Thread.sleep(100);
<span style="white-space:pre"> </span>} catch (InterruptedException e) {
<span style="white-space:pre"> </span>e.printStackTrace();
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>TimerManager.loop();
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>}
}