注解法实现定时任务Springboot

pom中添加依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-quartz</artifactId>
        </dependency>

yml添加配置

spring:
  task:
    scheduling:
      pool:     #任务调度线程池大小
        size: 1
      thread-name-prefix: springboot_     #调度线程任务前缀
      shutdown:
        await-termination: false    #线程池关闭时等待所有任务完成
        await-termination-period: 30s   #关闭前最大等待时间

主启动类添加注解

@SpringBootApplication
@EnableScheduling
public class Springboot6TaskApplication {

    public static void main(String[] args) {
        SpringApplication.run(Springboot6TaskApplication.class, args);
    }

}

行为方法添加注解

@Scheduled(cron = "0/10 * * * * ?")
    public void print(){
        System.out.println(Thread.currentThread().getName()+":Job0 is studying");
    }
}

打印的前面那个是该线程任务的名字。

格式还是以前的格式。启动就可以。

经验分享 程序员 微信小程序 职场和发展