Public class TimerService { public static final long p = 1000*60*60; Timer timer = new Timer(false); TimerSchedule schedule = null; public TimerService() { }
public void start() throws Exception { schedule = new TimerSchedule(); schedule.addTimerJob(new SomeTimerJob()); //add other job here timer.schedule(schedule,0,p); }
public void stop() throws Exception { timer.cancel(); } }
//包含了多個TimerJob,并每到一定時候取出來看看是否該調(diào)用 public class TimerSchedule extends TimerTask { PRivate List list = new ArrayList(); public TimerSchedule() {} public void addTimerJob(TimerJob job) { list.add(job); }
public void run() { Date now = Calendar.getInstance().getTime(); Date next = null; for(int i=0;i<list.size();i++) { TimerJob job = (TimerJob)list.get(i); next = job.getNextExeDate(); if(isEquals(now,next)) { job.execute(); } } }
/** * 比較倆個時間相差是否小于TimerService.p(一個周期) * @param now * @param next * @return */ private boolean isEquals(Date now,Date next) { long time = next.getTime()-now.getTime(); if (time <= TimerService.p && time >= 0) { return true; } else { return false; } }
public boolean cancel() { return true; } }
//該接口描述了如何完成TimerTask,請參考TimerJobExample interface TimerJob { public void execute(); public Date getNextExeDate(); }
/** * 該例子用于演示如何完成tiemrjob * 該例子功能是在天天的凌晨一點調(diào)用 */ public class TimerJobExample implements TimerJob { Calendar nextDate = null; public TimerJobExample() { nextDate = Calendar.getInstance(); nextDate.add(Calendar.DAY_OF_MONTH,1); //將設(shè)置調(diào)用時間是(第二天的)天天凌晨1點 nextDate.set(Calendar.HOUR_OF_DAY,1); } public void execute() { nextDate.add(Calendar.DAY_OF_MONTH,1); nextDate.set(Calendar.HOUR_OF_DAY,1); callFunction(); }
public Date getNextExeDate() { return nextDate.getTime(); }