Spring-Boot在启动时加载某个任务
比较简单的一个办法:
实现InitializingBean接口,实现afterPropertiesSet()方法,只要将预处理的代码写在这个方法里面即可
1 public class DayTradeTimer implements InitializingBean{ 2 /** 3 * 4 */ 5 private static final long serialVersionUID = -5173826987102711830L; 6 @SuppressWarnings("deprecation") 7 public void afterPropertiesSet() throws Exception { 8 // TODO Auto-generated method stub 9 Date date = new Date(); 10 //每天凌晨两点执行 11 if((date.getHours()==2 && date.getMinutes()>0) || (date.getHours()>2)){ 12 date.setDate(date.getDate()+1); 13 } 14 date.setHours(2); 15 date.setMinutes(0); 16 date.setSeconds(0); 17 Timer timer = new Timer(); 18 timer.scheduleAtFixedRate(new TimerTask() { 19 @Override 20 public void run() { 21 // TODO Auto-generated method stub 22 System.out.println("***********计时器*****************"); 23 } 24 }, date, 1000*60*60*24); 25 } 26 }