SpringBoot使用定时任务@Scheduled

最近在项目中遇到不少数据同步,定时审核、发布等需求,这时我们可以采用定时任务的方式去完成需求......

  • 定时任务的实现方式

Timer方式

Timer:JDK自带的java.util.Timer,底层是使用一个单线来实现多个Timer任务处理的,所有任务都是由同一个线程来调度,所有任务都是串行执行,意味着同一时间只能有一个任务得到执行,而前一个任务的延迟或者异常会影响到之后的任务

package com.ooliuyue.springboottask.task;

import java.time.LocalDateTime;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 基于Timer实现的定时调度,不推荐
 * @Auther: ly
 * @Date: 2019/1/2 15:53
 */

public class TimerDemo{
    public static void main(String[] args) {
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                System.out.println("执行任务" + LocalDateTime.now());
            }
        };
        Timer timer = new Timer();
        //在3秒后执行timerTask中的run方法,后面每5秒跑一次
        timer.schedule(timerTask,3000,5000);

    }
}

基于 ScheduledExecutorService

ScheduledExecutorService: JDK1.5新增的,位于java.util.concurrent包中;是基于线程池设计的定时任务类,每个调度任务都会被分配到线程池中,并发执行,互不影响。

package com.ooliuyue.springboottask.task;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: ly
 * @Date: 2019/1/2 16:22
 */

public class ScheduledExecutorServiceDemo {
    public static void main(String[] args) {
        ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool(10);
        scheduledExecutor.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                System.out.println("Hello World");
            }
            //3秒后每秒执行一次
        },3,3, TimeUnit.SECONDS);

    }
}

Spring Task

Spring Task: Spring3.0 以后新增了task,一个轻量级的Quartz,功能够用,用法简单。
接下来讲述如何在SpringBoot中使用。

  • 导入依赖

在 pom.xml 中添加 spring-boot-starter-web 依赖即可,它包含了spring-context,定时任务相关的就属于这个JAR下的org.springframework.scheduling包中


            org.springframework.boot
            spring-boot-starter-web

  • 定时任务
package com.ooliuyue.springboottask.task;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @Auther: ly
 * @Date: 2019/1/2 17:12
 */
@Component
public class SpringTaskDemo {

    private static final Logger log = LoggerFactory.getLogger(SpringTaskDemo.class);

    @Async //代表该任务可以进行异步工作,由原本的串行改为并行
    @Scheduled(cron = "0/1 * * * * *") //定时任务的核心
    public void scheduled1() throws InterruptedException {
        Thread.sleep(3000);
        log.info("scheduled1 每1秒执行一次 :{}", LocalDateTime.now());
    }
}

  • 主函数
package com.ooliuyue.springboottask;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

/**
  @EnableAsync 注解表示开启@Async注解的解析;作用就是将串行化的任务给并行化了。
  (@Scheduled(cron = "0/1 * * * * *")假设第一次工作时间为2018-05-29 17:30:55,工作周期为3秒;
  如果不加@Async那么下一次工作时间就是2018-05-29 17:30:59;
  如果加了@Async 下一次工作时间就是2018-05-29 17:30:56)
 */
@EnableAsync

/**
 @EnableScheduling 注解表示开启对@Scheduled注解的解析;
 同时new ThreadPoolTaskScheduler()也是相当的关键,
 通过阅读过源码可以发现默认情况下的 private volatile int poolSize = 1;
 这就导致了多个任务的情况下容易出现竞争情况(多个任务的情况下,如果第一个任务没执行完毕,后续的任务将会进入等待状态)
 */
@EnableScheduling  //开启对@Scheduled注解的解析
@SpringBootApplication
public class SpringbootTaskApplication {

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

    /**
     * 默认情况下 TaskScheduler 的 poolSize = 1
     * @return 线程池
     */
    @Bean
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(10);
        return taskScheduler;
    }

}

  • 测试

完成准备事项后,启动SpringbootTaskApplication ,观察日志信息如下

2019-01-02 18:05:40.043  INFO 9920 --- [cTaskExecutor-1] c.o.springboottask.task.SpringTaskDemo   : scheduled1 每1秒执行一次 :2019-01-02T18:05:40.043
2019-01-02 18:05:41.002  INFO 9920 --- [cTaskExecutor-2] c.o.springboottask.task.SpringTaskDemo   : scheduled1 每1秒执行一次 :2019-01-02T18:05:41.002
2019-01-02 18:05:42.001  INFO 9920 --- [cTaskExecutor-3] c.o.springboottask.task.SpringTaskDemo   : scheduled1 每1秒执行一次 :2019-01-02T18:05:42.001
2019-01-02 18:05:43.001  INFO 9920 --- [cTaskExecutor-4] c.o.springboottask.task.SpringTaskDemo   : scheduled1 每1秒执行一次 :2019-01-02T18:05:43.001
2019-01-02 18:05:44.001  INFO 9920 --- [cTaskExecutor-5] c.o.springboottask.task.SpringTaskDemo   : scheduled1 每1秒执行一次 :2019-01-02T18:05:44.001
2019-01-02 18:05:45.001  INFO 9920 --- [cTaskExecutor-6] c.o.springboottask.task.SpringTaskDemo   : scheduled1 每1秒执行一次 :2019-01-02T18:05:45.001
2019-01-02 18:05:46.001  INFO 9920 --- [cTaskExecutor-7] c.o.springboottask.task.SpringTaskDemo   : scheduled1 每1秒执行一次 :2019-01-02T18:05:46.001
2019-01-02 18:05:47.002  INFO 9920 --- [cTaskExecutor-8] c.o.springboottask.task.SpringTaskDemo   : scheduled1 每1秒执行一次 :2019-01-02T18:05:47.002
2019-01-02 18:05:48.001  INFO 9920 --- [cTaskExecutor-9] c.o.springboottask.task.SpringTaskDemo   : scheduled1 每1秒执行一次 :2019-01-02T18:05:48.001

github
码云

你可能感兴趣的:(SpringBoot使用定时任务@Scheduled)