1.在启动类上加@EnableScheduling注解
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableScheduling
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
2.在创建定时任务的类上加上@Component,并在方法上加@Scheduled(cron="")
package com.example.demo.com.example.demo.controller;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class TimeJob {
@Scheduled(cron = "0/1 * * * * ?")
public void task1(){
System.out.println(Thread.currentThread().getName()+"-----------------------01");
}
@Scheduled(cron = "0/1 * * * * ?")
public void task2(){
System.out.println(Thread.currentThread().getName()+"-----------------------02");
}
@Scheduled(cron = "0/1 * * * * ?")
public void task3(){
System.out.println(Thread.currentThread().getName()+"-----------------------03");
}
public void task4(){
System.out.println(Thread.currentThread().getName()+"-----------------------0m");
}
}
3.注意配一个任务的线程池,不然所有的定时任务走同一个线程;影响效率.定时任务的config如下:
package com.example.demo.com.example.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
@Configuration
public class TaskSchedulerConfig {
@Bean
public ThreadPoolTaskScheduler taskScheduler(){
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(3);
threadPoolTaskScheduler.setThreadNamePrefix("spring-boot-task");
return threadPoolTaskScheduler;
}
}
4.运行结果如下