转自:https://blog.csdn.net/weweeeeeeee/article/details/91444616

在我们开发项目过程中,经常需要定时任务来帮助我们来做一些内容, Spring Boot 默认已经帮我们实行了,只需要添加相应的注解就可以实现

1、pom 包配置

pom 包里面只需要引入 Spring Boot Starter 包即可

  1.  
    <dependencies>
  2.  
    <dependency>
  3.  
    <groupId>org.springframework.boot</groupId>
  4.  
    <artifactId>spring-boot-starter</artifactId>
  5.  
    </dependency>
  6.  
    <dependency>
  7.  
    <groupId>org.springframework.boot</groupId>
  8.  
    <artifactId>spring-boot-starter-test</artifactId>
  9.  
    <scope>test</scope>
  10.  
    </dependency>
  11.  
    </dependencies>

2、启动类启用定时

在启动类上面加上@EnableScheduling即可开启定时

  1.  
    @SpringBootApplication
  2.  
    @EnableScheduling
  3.  
    public class Application {
  4.  
     
  5.  
    public static void main(String[] args) {
  6.  
    SpringApplication.run(Application.class, args);
  7.  
    }
  8.  
    }

3、创建定时任务实现类

定时任务1:

  1.  
    @Component
  2.  
    public class SchedulerTask {
  3.  
     
  4.  
    private int count=0;
  5.  
     
  6.  
    @Scheduled(cron="*/6 * * * * ?")
  7.  
    private void process(){
  8.  
    System.out.println("this is scheduler task runing "+(count++));
  9.  
    }
  10.  
     
  11.  
    }

定时任务2:

  1.  
    @Component
  2.  
    public class Scheduler2Task {
  3.  
     
  4.  
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
  5.  
     
  6.  
    @Scheduled(fixedRate = 6000)
  7.  
    public void reportCurrentTime() {
  8.  
    System.out.println("现在时间:" + dateFormat.format(new Date()));
  9.  
    }
  10.  
     
  11.  
    }

结果如下:

  1.  
    this is scheduler task runing 0
  2.  
    现在时间:09:44:17
  3.  
    this is scheduler task runing 1
  4.  
    现在时间:09:44:23
  5.  
    this is scheduler task runing 2
  6.  
    现在时间:09:44:29
  7.  
    this is scheduler task runing 3
  8.  
    现在时间:09:44:35

--------------------------------------------------- 

posted on 2020-09-21 13:42  Sharpest  阅读(281)  评论(0编辑  收藏  举报