springboot 定時器使用
1.在啓動類添加定時器啓動註解
@SpringBootApplication
@EnableTransactionManagement
@EnableScheduling//啓動定時器
public class BuildingboardApplication {
public static void main(String[] args) {
SpringApplication.run(BuildingboardApplication.class, args);
}
2.創建一個類 使用 @Scheduled(cron = “xxxxxx”)在方法上就能夠啓動定時器
cron 表達式生成器
@Component
public class TimerTask {
private static final Logger log = LogManager.getLogger(TimerTask.class);
@Autowired
private CourseInfolmpl courseInfolmpl;
//定時器測試
@Scheduled(cron = "0/2 * * * * ? ")// 間隔2秒執行
public void testTimerTask(){
log.info("定時器測試");
}
java.util.Timer; 定時器
//每天在凌晨2點執行
public void clearCache() {
Timer timer = new Timer();
//Calendar這個專門用於對日期進行操作的類
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 02);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date time = calendar.getTime();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// 設置支持任務
}
}, time, 1000 * 60 * 60 * 24); //第一個參數是幾時執行 第二個參數是執行週期
}
timer.schedule也能夠執行定時任務
兩個方法的區別是 如果中間出現問題scheduleAtFixedRate會按照原來的時間完成 而schedule這不會按照原來時間完成 而是要超時完成