使用注解@ComponentScan会扫描指定的包
使用注解@EnableScheduling开启定时任务,会自动扫描
定义@Component作为组件被容器扫描
ScheduleApplication.java
@SpringBootApplication
//扫描所有需要的包,包含一些自用的工具类包所在的路径
@ComponentScan("taskScheduler")
//开启定时任务
@EnableScheduling
public class ScheduleApplication {
public static void main(String[] args) {
SpringApplication.run(ScheduleApplication.class,args);
}
}
TestTask.java
@Component
public class TestTask {
private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
//定义每过3秒执行任务
@Scheduled(fixedRate = 3000)
public void reportCurrentTime(){
System.out.println("每隔3秒执行一次, 现在时间:"+simpleDateFormat.format(new Date()));
}
@Scheduled(cron = "0 33 22 ? * *") //每天的晚上十点33分执行一次
public void fixTimeExecution() {
System.out.println("在指定时间内执行一次: " + simpleDateFormat.format(new Date()) + "执行");
}
}