spring boot: @EnableScheduling开启计划任务支持,@Scheduled计划任务声明
1.pom.xml 引入依赖
<dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.1.7</version> </dependency>
2.在启动类上添加注解 @EnableScheduling
@SpringBootApplication @EnableScheduling public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
3.测试类
import java.util.Date; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; /*** * * Quartz设置项目全局的定时任务 * @Component注解的意义 泛指组件 * @author * */ @Component public class QuartzTask { @Scheduled(cron = "0 0/1 * * * ?") // 每分钟执行一次 public void work() throws Exception { System.out.println("执行调度任务:" + new Date()); } @Scheduled(fixedRate = 5000) // 每5秒执行一次 public void play() throws Exception { System.out.println("每5秒执行一次执行Quartz定时器任务:" + new Date()); } @Scheduled(cron = "0/2 * * * * ?") // 每2秒执行一次 public void doSomething() throws Exception { System.out.println("每2秒执行一个的定时任务:" + new Date()); } @Scheduled(cron = "0 45 17 ? * *") // 每天17:45:00执行 public void goWork() throws Exception { System.out.println("每天17:45:00执行一次的定时任务:" + new Date()); } }
4.结果