前言
我们经常会用到定时任务,直接用Thread显然不合适,这里我们采用calendar,封装好的一个线程任务,来实现定时任务
代码
package com;
import java.util.TimerTask;
public class NFDFlightDataTimerTask extends TimerTask {
@Override
public void run() {
try {
//需要循环的内容
} catch (Exception e) {
}
}
}
package com;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
public class TimerManager {
// private static final long PERIOD_DAY = 24 * 60 * 60 * 1000;
// 相隔多长时间执行一次
private static final long PERIOD_DAY = 15 * 60 * 1000;
public TimerManager(String startUrl) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 15);
calendar.set(Calendar.MINUTE, 57);
calendar.set(Calendar.SECOND, 0);
Date date = calendar.getTime();
if (date.before(new Date())) {
date = this.addDay(date, 15);
}
Timer timer = new Timer();
NFDFlightDataTimerTask task = new NFDFlightDataTimerTask(startUrl);
timer.schedule(task, date, PERIOD_DAY);
}
public Date addDay(Date date, int num) {
Calendar startDT = Calendar.getInstance();
startDT.setTime(date);
// 设置上次执行时间
startDT.add(Calendar.MINUTE, num);
return startDT.getTime();
}
}
核心代码就上面那部分,测试的时候,直接main方法
new TimerManager();即可