定时器的用法是java核心基础之一,很多特殊功能都需要用到定时器,下面一起来看看定时器是如何编写的吧。
示例:一个具备周期性定时(毫秒级);单时刻定时(秒级);多时刻定时(秒级)。后两个时间的设置必须符合“yyyy-MM-dd HH:mm:ss”、“yyyy-MM-dd ”、“HH:mm:ss”、“HH:mm”、“yyyy-MM-dd HH”、“yyyy-MM-dd HH:mm”格式的定时器
Java代码
//TimerTask代码 import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; public abstract class TimerTask implements Runnable { private long period = -1; private String time; private List < String > timeList; private boolean isCancel = false; private boolean isFormart = false; public long getPeriod() { return period; } public void setPeriod(long period) { this.period = period; } public void setTime(String time) { this.time = time; } public String getTime() { return time; } public List < String > getTimeList() { return timeList; } public void setTimeList(List < String > timeList) { this.timeList = timeList; } public void cancel() { this.isCancel = true; } public boolean isCancel() { return isCancel; } public abstract void execute(); public void run() { //格式化传入的日期或日期时间或时间参数 if (!this.isFormart) { this.fomart(); } //确保指定的运行点在一秒钟内只运行一次 boolean isRun = false; //确保多个运行点中,每个运行点在一秒钟内只运行一次 int flag[] = null; try { flag = new int[this.timeList.size()]; } catch (Exception e) {} SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //当没有被取消时 while (!isCancel) { String dt = sdf.format(new Date()); if (this.period > 0) { try { Thread.sleep(this.period); } catch (Exception e) {} this.execute(); } else if (this.time != null) { if (this.time.indexOf("-") > 0) { if (this.time.equals(dt) && !isRun) { isRun = true; this.execute(); } } else { if (this.time.equals(dt.substring(11)) && !isRun) { isRun = true; this.execute(); } } } else if (this.timeList != null) { int loopIndex = 0; for (String dateTime: this.timeList) { if (dateTime.indexOf("-") > 0) { if (dateTime.equals(dt) && flag[loopIndex] == 0) { this.execute(); flag[loopIndex] = 1; } } else { if (dateTime.equals(dt.substring(11)) && flag[loopIndex] == 0) { this.execute(); flag[loopIndex] = 1; } } ++loopIndex; } } } } private void fomart() { if (!this.isFormart) { if (this.time != null) { this.time = this.format(this.time); } if (this.timeList != null) { for (int i = 0; i < this.timeList.size(); i++) { String dateTime = this.timeList.get(i); if (dateTime != null) { this.timeList.set(i, format(dateTime)); } } } } else { this.isFormart = true; } } private String format(String datetime) { if (datetime != null) { // 是否含有减号 boolean hasSubtrSign = datetime.contains("-"); // 是否含有冒号 boolean hasColonSign = datetime.contains(":"); // 12-23 12:33 if (hasSubtrSign == true && hasColonSign == true) { datetime = DateUtil.formatToEnglish(datetime); } else if (hasSubtrSign && hasColonSign == false) { datetime = DateUtil.formatToEnglish(datetime); } else if (hasSubtrSign == false && hasColonSign) { datetime = DateUtil.formatToEnglish(datetime) .substring(11); } } return datetime; } } /////////////////////////////////////////////////////////////////// //Timer代码 import java.util.ArrayList; public class Timer extends Thread { private boolean isStart = false; private boolean isCannel = false; ArrayList < TimerTaskBean > tasks = new ArrayList < TimerTaskBean > (); public Timer() {} public void cancel() { this.isCannel = true; } public boolean isCannel() { return isCannel; } public void schedule(TimerTask task, long period) { task.setPeriod(period); //添加任务 this.addTask(task); } public void schedule(TimerTask task, long delay, long period) { try { Thread.sleep(delay); } catch (Exception e) {} task.setPeriod(period); //添加任务 this.addTask(task); } public void schedule(TimerTask task, String time) { task.setTime(time); //添加任务 this.addTask(task); } public void schedule(TimerTask task, long delay, String time) { try { Thread.sleep(delay); } catch (Exception e) {} task.setTime(time); //添加任务 this.addTask(task); } public void schedule(TimerTask task, java.util.List < String > timeList) { task.setTimeList(timeList); //添加任务 this.addTask(task); } public void schedule(TimerTask task, long delay, java.util.List < String > timeList) { try { Thread.sleep(delay); } catch (Exception e) {} task.setTimeList(timeList); //添加任务 this.addTask(task); } //添加任务 private void addTask(TimerTask task) { boolean isExist = false; for (TimerTaskBean ttBean: this.tasks) { if (task.equals(ttBean.getTask())) { isExist = true; break; } else { isExist = false; } } if (!isExist) { tasks.add(new TimerTaskBean(task, false)); } //判断定时器线程是否启动 if (!this.isStart) { this.start(); this.isStart = true; } } public void run() { // 是否取消所有任务的定时功能 while (!this.isCannel) { for (int i = 0; i < tasks.size(); i++) { TimerTaskBean ttBean = tasks.get(i); //判断是否开始运行 if (ttBean != null && !ttBean.isRun()) { ttBean.setRun(true); new Thread(ttBean.getTask()) .start(); } } } //当取消定时器时,取消所有任务 if (this.isCannel) { for (TimerTaskBean ttBean: tasks) { ttBean.getTask() .cancel(); } } } class TimerTaskBean { public TimerTaskBean() {} public TimerTaskBean(TimerTask task, boolean isRun) { this.task = task; this.isRun = isRun; } private boolean isRun = false; private TimerTask task = null; public boolean isRun() { return isRun; } public void setRun(boolean isRun) { this.isRun = isRun; } public TimerTask getTask() { return task; } public void setTask(TimerTask task) { this.task = task; } } } //////////////////////////////////////////////////////////////// //TimerTest代码 import java.util.ArrayList; public class TimerTest { public static void main(String[] args) { Timer t = new Timer(); T1 t1 = new T1(); T2 t2 = new T2(); t.schedule(t1, 1000); ArrayList < String > list = new ArrayList < String > (); list.add("11:44:30"); list.add("11:44:31"); list.add("11:44:32"); list.add("11:44:33"); list.add("11:44:34"); list.add("11:44:35"); list.add("11:44:36"); list.add("11:44:37"); t.schedule(t1, list); try { Thread.sleep(1000 * 4); } catch (Exception e) {} t1.cancel(); //取消任务1,任务2线程停止 t.schedule(t2, 1000); t.schedule(t2, list); try { Thread.sleep(1000 * 4); } catch (Exception e) {} t2.cancel(); //取消任务2,任务2线程停止 try { Thread.sleep(1000 * 4); } catch (Exception e) {} t.cancel(); //取消定时器,定时器线程停止 } } class T1 extends TimerTask { public T1() {} public void execute() { System.out.println(11111111); } } class T2 extends TimerTask { public T2() {} public void execute() { System.out.println(22222222); } }
以上就是今天的全部内容,想知道更多详细java基础知识就请继续关注我们了解详情吧。
推荐阅读: