1.不规定时间
Calendar calendar = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
calendar.add(Calendar.DAY_OF_MONTH,1);//每隔一天执行一次
//calendar.add(Calendar.SECOND,10);
System.out.println(format.format(calendar.getTime()));
Timer timer= new Timer();
CustomerMapJob myTimeTask =new CustomerMapJob();
timer.schedule(myTimeTask,calendar.getTime());
2.凌晨1点定时跑
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 1); //凌晨1点
calendar.set(Calendar.MINUTE, 0);//分
calendar.set(Calendar.SECOND, 0);//秒
Date date=calendar.getTime(); //第一次执行定时任务的时间
//如果第一次执行定时任务的时间 小于当前的时间
//此时要在 第一次执行定时任务的时间加一天,以便此任务在下个时间点执行。如果不加一天,任务会立即执行。
if (date.before(new Date())) {
date = this.addDay(date,1);
}
Timer timer = new Timer();
//安排指定的任务在指定的时间开始进行重复的固定延迟执行。
CustomerMapJob myTimeTask =new CustomerMapJob();
timer.schedule(myTimeTask,date,24 * 60 * 60 * 1000);
}
// 增加或减少天数
public Date addDay(Date date,int num) {
Calendar startDT = Calendar.getInstance();
startDT.setTime(date);
startDT.add(Calendar.DAY_OF_MONTH, num);
return startDT.getTime();
}
public class NumberAnalysisMapJob extends TimerTask {
private static final Logger LOGGER = LoggerFactory.getLogger(NumberAnalysisMapJob.class);
@Override
public void run(){
final NumberAnalysisMapService numberAnalysisMapService =(NumberAnalysisMapService) ApplicationContextHelper.getInstance().getBean(NumberAnalysisMapService.class);
LOGGER.info("begin to sync address");
try{
numberAnalysisMapService.sync();
}catch (final Throwable e){
LOGGER.error("",e);
}
LOGGER.info("end sync address");
}
}