java自行实现单线程定时器

时间:2022-06-03 23:33:34

由于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>}


}