1.首页在启动文件里开启定时任务注解
@EnableScheduling
2.编写好定时任务类
import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import java.time.LocalDateTime; /** * @author 兵兵有你 * @date 2021/10/11 0011 10:48 * @Email 1360968945@qq.com */ @Configuration @EnableScheduling //开启定时任务 //@EnableAsync //异步执行 public class StaticScheduleTask { //@Scheduled(cron = "0/5 * * * * ?") //执行方式1-每5秒1次 //@Async //异步执行 @Scheduled(fixedRate = 5000) //执行方式2 -每5秒一次 public void configureTasks(){ System.out.println(Thread.currentThread()+"执行任务的时间是"+ LocalDateTime.now()); } }
如果开启了异步执行,每次定时任务都会开启一个新线程