定时任务.
相关接口.
TaskScheduler
调度TaskExecutor
执行
相关注解.
@EnableScheduling
添加在入口类,开启定时功能@Scheduled
确定什么时候执行
使用.
启动类上添加 @EnableScheduling
注解.
@EnableScheduling
@SpringBootApplication
public class TaskApplication {
public static void main(String[] args) {
SpringApplication.run(TaskApplication.class, args);
}
}
编写业务类.
方法上添加 @Scheduled
@Service
public class ScheduledService {
// cron表达式 计划任务
// 秒(0-59) 分(0-59) 时(0-23) 日(1-31) 月(1-12) 星期(0-7,0和7表示的都是星期日)
/*
*: 所有
/: 每 ==> * / 2 每2个单位 ==> 1 / 2 从第一个单位开始,每两个单位发生一次
-: 数字到数字
,: 分开几个离散的数字
?: 不指定值 -- 用于 日 和 星期
#: 确定每个月的第几个星期几 2#3 每月第二个星期三
*/
@Scheduled(cron = "*/3 * * * * ?") // 每3秒
public void hello(){
System.out.println("hello");
}
}