当前位置:   article > 正文

Spring Boot使用@Scheduled注解实现定时任务_springboot集成使用@scheduled

springboot集成使用@scheduled

Spring Boot定时任务的实现

在日常开发中,spring boot给我们集成了定时任务的依赖,只需要将依赖导入进行配置即可

1.引入Spring Boot依赖

<dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-web</artifactid>
</dependency>
  • 1
  • 2
  • 3
  • 4

2.在Spring Boot的启动类中使用@EnableScheduling 注解,用来开启定时任务

/**
 * 项目入口类
 */
@EnableScheduling //定时任务在启动类注解
@SpringBootApplication
public class DemoScheduleApplication {

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

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

3.在想要执行定时任务的方法上使用@Scheduled注解

@Component //定时任务在类上的注解
public class Schedule {

    /**
     * initialDelay 第一次启动任务延迟时间(单位 毫秒)
     * fixedRate    每次任务间隔时间 (单位 毫秒)
     */
    @Scheduled(initialDelay = 1000,fixedRate = 3000) //定时任务在方法上的注解
    public void timedA(){
        System.out.println("延迟3秒启动  "+new Date());
    }

    /**
     * cron 表达式 秒 分 时 天 月 年
     * cron = "10 44 21 * * ?" 表示每天 21点 44分 10秒 开始执行
     */
    @Scheduled(cron = "10 44 21 * * ?") //定时任务在方法上的注解
    public void timedB(){
        System.out.println("每天 21点 44分 10秒 开始执行  "+new Date());
    }


}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

注意:使用@Scheduled注解标注的方法所在的类需要能被Spring所管理,并且能被扫描到

推荐两个定时任务表达式生成器
链接: https://www.toolzl.com/tools/croncreate.html
链接: https://cron.qqe2.com/

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号