1、SpringBoot项目的启动类上加@EnableScheduling注解,开启定时任务
@EnableScheduling
@SpringBootApplication
public class TasktestApplication {
public static void main(String[] args) {
SpringApplication.run(TasktestApplication.class, args);
}
}
2、创建一个定时任务类,在类上加@Component注解,在方法上加@Scheduled注解
@Component
public class TimingTaskService {
@Scheduled(cron = "0 0/2 * * * ?")
public void test(){
System.out.println("开启定时任务,每两分钟执行一次任务");
}
//12月15日17点00-03分10-20秒执行
@Scheduled(cron = "10-20 00-03 17 15 12 ?")
public void test(){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("成功"+simpleDateFormat.format(new Date()));
}
}
</