java定时任务实现方法:
public class TimingTask {
private static int count = 0;
private static SpiderService service = null;
public static void startTask(int hour,int minute,int second) {
TimerTask task = new TimerTask() {
@Override
public void run() {
service = new SpiderService();
service.service();
++count;
System.out.println("时间=" + new Date() + " 执行了" + count + "次"); // 1次
}
}; //设置执行时间
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);//每天
//定制每天的21:09:00执行,
calendar.set(year, month, day, hour, minute, second);
Date date = calendar.getTime();
Timer timer = new Timer();
System.out.println(date); // int period = 2 * 1000;
//每天的date时刻执行task,每隔2秒重复执行
// timer.schedule(task, date, period);
//每天的date时刻执行task, 仅执行一次
timer.schedule(task, date);
}
调用方法:
public static void main(String[] args) {
//下面是两个任务
TimingTask.startTask(11, 40, 00);
TimingTask.startTask(11, 45, 00);
}