效果展示:
代码
一、开启定时任务
//启动类
@SpringBootApplication
@EnableScheduling//开启定时任务 必须有
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
二、具体要执行的定时任务
@Component//装配到spring容器
public class SchedulerTask {
private int count = 0;
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(cron = "*/6 * * * * ?")
private void process() {
System.out.println("这是自动累加的定时任务: " + (count++));
}
@Scheduled(fixedRate = 6000)
public void reportCurrentTime() {
System.out.println("这是自动显示当前时间的定时任务:" + dateFormat.format(new Date()));
}
}
@Scheduled
(1)标注在具体要执行的定时任务上,spring容器会对其实时监控。但是前提是得把所在的类交给spring容器进行管理。
我具体工作的定时任务是放在@Service标注的业务层,这里的案例就直接用@Component交给Spring容器。
@Scheduled(cron = "*/6 * * * * ?")
(1)cron = "*/6 * * * * ?" 表达式,这里直接去这里看。连接:定时任务之cron表达式
(2)但是在实际开发中怎么使用呢?
是使用cron = "${自定义名称}" 这种方式,将表达式定义在application.properties中的。直接在具体的定时任务方法中取到要 执行的时间格式。
application.properties中的格式是这样的
cron=0 0 0 * * ?