定时执行任务一般可以使用新建一个线程,让循环执行,这里就介绍下使用Quartx来进行定时执行任务
Maven引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
在SpringBoot的启动类加上注解@EnableScheduling
@SpringBootApplication
@EnableScheduling //添加注解
public class QuartzDemoApplication {
public static void main(String[] args) {
SpringApplication.run(QuartzDemoApplication.class, args);
}
}
新建一个普通类,并在类上加上注解@Component,在要定时执行的方法上也加上注解@Scheduled
@Component
public class PrintHelloWorldJob {
//https://cron.qqe2.com/ 可以进入这个网站看看关于@Scheduled注解对应参数的格式
@Scheduled(cron ="0/3 0/1 * * * ?")
public void printHelloWorld(){
System.out.println("===============hello world================");
}
}