Spring Boot 定时任务

在没有接触Spring Boot之前,我们通常都是用java.util包中自带的Timer类来实现

public class TestTimer {
    public static void main(String[] args) {
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                System.out.println("task  run:"+ new Date());
            }
        };
        Timer timer = new Timer();
        //安排指定的任务在指定的时间开始进行重复的固定延迟执行。这里是每3秒执行一次
        timer.schedule(timerTask,10,3000);
    }
}

Spring3.0以后自带了task,使用@EnableScheduling即可创建不同的定时任务

串行式

创建任务类

@Slf4j
@Component
public class ScheduledTasks {

    /**
     * 上一次开始执行时间点之后5秒再执行,每次执行间隔时间5秒
     */
    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime1() {
        log.info("fixedRate :" + new Date());
    }

    /**
     * 上一次执行完毕时间点之后5秒再执行,距上次执行完成后间隔5秒开始执行下次任务
     */
    @Scheduled(fixedDelay = 5000)
    public void reportCurrentTime2() {
        log.info("fixedDelay:" + new Date());
    }

    /**
     * 第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次
     */
    @Scheduled(initialDelay = 1000, fixedDelay = 5000)
    public void reportCurrentTime3() {
        log.info("fixedDelay:" + new Date());
    }

    /**
     * 通过cron表达式定义规则
     */
    @Scheduled(cron = "0/5 * * * * *")
    public void reportCurrentTime4() {
        log.info("cron:" + new Date());
    }
}

然后在主类上加上@EnableScheduling注解,即可运行任务


运行结果图

如果使用串行式,可以注意到所有的定时任务都是通过一个线程执行,这样当某个定时任务出问题时,整个都会崩溃。所以推荐大家使用多线程来执行定时任务

并行式

很简单我们只需创建一个类继承SchedulingConfigurer接口

@Configuration
public class ScheduledConfig implements SchedulingConfigurer {
   @Override
   public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
       scheduledTaskRegistrar.setScheduler(setTaskExecutors());
   }

   @Bean()
   public Executor setTaskExecutors(){
       //创建一个基本大小为3的线程池
       return Executors.newScheduledThreadPool(3);
   }
}

然后运行主类即可


运行截图

可以看到每个任务都是用不同的线程来执行,这样就比较安全了

cron语法

常用: 秒、分、时、日、月、年

0 0 10,14,16 * * ? 每天上午10点,下午2点,4点
0 0 12 * * ? 每天中午12点触发
0 0/5 0 * * ? 每5分钟执行一次

更多语法请参考传送门

参考文章
http://www.wanqhblog.top/2018/02/01/SpringBootTaskSchedule/
https://blog.csdn.net/onedaycbfly/article/details/79093829

你可能感兴趣的:(Spring Boot 定时任务)