SpringBoot中实现定时任务的两种方式:基于注解(@Scheduled)的简单定时器,基于接口SchedulingConfigurer实现的动态定时任务

代码目录结构

在这里插入图片描述

配置文件application.yml内容

#设置定时任务
task:
  taskName1: #任务名称
    switch: true #是否开启定时任务
    cron: "0/5 * * * * ?" #任务表达式
  taskName2: #任务名称
    switch: true #是否开启定时任务
    cron: "0/5 * * * * ?" #任务表达式

启动类

package com.example.schedule;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ScheduleApplication {

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

基于注解(@Scheduled)的简单定时器

package com.example.schedule.SimpleSchedule;

import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDateTime;

/**
 * @fileName:Schedule
 * @createTime:2019/5/14 17:16
 * @author:
 * @version:
 * @description:基于注解(@Scheduled)的简单定时器demo
 *
 * cron表达式语法:[秒] [分] [小时] [日] [月] [周] [年]
 * @Scheduled(fixedDelay = 5000) //上一次执行完毕时间点之后5秒再执行
 * @Scheduled(fixedDelayString = "5000") //上一次执行完毕时间点之后5秒再执行
 * @Scheduled(fixedRate = 5000) //上一次开始执行时间点之后5秒再执行
 * @Scheduled(initialDelay=1000, fixedRate=5000) //第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次
 *
 */


//1.主要用于标记配置类
@Configuration
// 2.开启定时任务
@EnableScheduling
public class Schedule {
    //3.添加定时任务
    @Scheduled(cron = "0/5 * * * * ?")
    //或直接指定时间间隔,例如:5秒
    //@Scheduled(fixedRate=5000)

    private void configureTasks() {
        System.err.println("基于注解(@Scheduled)的简单定时器demo: " + LocalDateTime.now());
    }
}

基于接口SchedulingConfigurer的动态定时任务

此种方法实现SchedulingConfigurer 类,采用多线程方式跑定时任务,所以模拟了两个实现类

配置类:

package com.example.schedule.ConfigurerSchedule;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.util.StringUtils;

import java.util.concurrent.*;

/**
 * @fileName:ConfigurerScheduling
 * @createTime:2019/5/14 17:26
 * @author:
 * @version:
 * @description:基于接口SchedulingConfigurer的动态定时任务
 */

@Configuration
@EnableScheduling
public abstract class ConfigurerScheduling implements SchedulingConfigurer {

    /**
     * @brief 定时任务名称
     */
    private String schedulerName;

    /**
     * @brief 定时任务周期表达式
     */
    private String cron;

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.setScheduler(taskScheduler());
        scheduledTaskRegistrar.addTriggerTask(
                //执行定时任务
                () -> {
                    processTask();
                },
                //设置触发器
                triggerContext -> {
                    // 初始化定时任务周期
                    if (StringUtils.isEmpty(cron)) {
                        cron = getCron();
                    }
                    CronTrigger trigger = new CronTrigger(cron);
                    return trigger.nextExecutionTime(triggerContext);
                }
        );
    }

    /**
     * 设置TaskScheduler用于注册计划任务
     *
     * @return
     */
    @Bean(destroyMethod = "shutdown")
    public Executor taskScheduler() {
        //设置线程名称
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build();
        //创建线程池
        return Executors.newScheduledThreadPool(5, namedThreadFactory);
    }

    /**
     * @brief 任务的处理函数
     * 本函数需要由派生类根据业务逻辑来实现
     */
    protected abstract void processTask();


    /**
     * @return String
     * @brief 获取定时任务周期表达式
     * 本函数由派生类实现,从配置文件,数据库等方式获取参数值
     */
    protected abstract String getCron();
}


实现类1

package com.example.schedule.ConfigurerSchedule.task;

import com.example.schedule.ConfigurerSchedule.ConfigurerScheduling;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

/**
 * @fileName:TaskDemo1
 * @createTime:2019/5/20 10:07
 * @author:
 * @version:
 * @description:
 */

@Configuration
public class TaskDemo1 extends ConfigurerScheduling {

    @Value(value = "${task.taskName1.switch}")
    private Boolean isSwitch;

    @Value(value = "${task.taskName1.cron}")
    private String cron;

    @Override
    protected void processTask() {
        if (isSwitch){
            System.out.println("基于接口SchedulingConfigurer的动态定时任务:"
                    + LocalDateTime.now()+",线程名称:"+Thread.currentThread().getName()
                    + " 线程id:"+Thread.currentThread().getId());
        }
    }

    @Override
    protected String getCron() {
        return cron;
    }
}


实现类2

package com.example.schedule.ConfigurerSchedule.task;

import com.example.schedule.ConfigurerSchedule.ConfigurerScheduling;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

/**
 * @fileName:TaskDemo2 
 * @createTime:2019/5/20 10:07
 * @author:
 * @version:
 * @description:
 */

@Configuration
public class TaskDemo2 extends ConfigurerScheduling {

    @Value(value = "${task.taskName2.switch}")
    private Boolean isSwitch;

    @Value(value = "${task.taskName2.cron}")
    private String cron;

    @Override
    protected void processTask() {
        if (isSwitch) {
            System.out.println("基于接口SchedulingConfigurer的动态定时任务:"
                    + LocalDateTime.now() + ",线程名称:" + Thread.currentThread().getName()
                    + " 线程id:" + Thread.currentThread().getId());
        }
    }

    @Override
    protected String getCron() {
        return cron;
    }
}


运行结果

在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值