SpringBoot定时器应用纪要
背景: 公司项目部分数据需要动态刷新过期数据,因此需要设置定时任务.
特此纪要.
问题: SpringBoot如何实现定时任务?
说明: SpringBoot实现定时任务主要有三种方式:
1. 静态方式: 基于注解.
2. 动态方式: 基于接口.
3. 多线程定时任务.
时间点设定规则:
秒(0~59) 例如0/5表示每5秒
分(0~59)
时(0~23)
日(0~31)的某天,需计算
月(0~11)
周几( 可填1-7 或 SUN/MON/TUE/WED/THU/FRI/SAT)
此处项目应用第一种方式,因此简单演示第一种基于注解方式的实现:
为了更方便直观的了解该问题,下面给出对应实现代码:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
@Configuration
@EnableScheduling
public class ScheduleConfig {
@Autowired
@SuppressWarnings("all")
private xxxxMapper xxxxMapper;
@Scheduled(cron = "0 0/30 * * * ?")
public void timingProce() {
// Codding.....
// xxxxMapper.list(Entity entity);
Date date = new Date();
DateFormat mediumDateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
System.out.println("thirty min .........." + mediumDateFormat.format(date));
}
}