springboot实现动态定时任务

本文详细介绍了如何在Spring Boot项目中使用Quartz框架实现动态定时任务,包括引入依赖、创建任务工厂、抽象类、业务实现、任务管理器、启动类以及测试案例。并推荐了一个Cron表达式生成器辅助配置定时任务。
摘要由CSDN通过智能技术生成

1、maven引入quartz包

<!-- https://mvnrepository.com/artifact/org.quartz-scheduler/quartz -->
<dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz</artifactId>
    <version>2.3.2</version>
</dependency>

2、创建定时任务工厂类

/**
 * 定时任务工厂类
 */
@Component
public class JobFactory extends SpringBeanJobFactory implements ApplicationContextAware {
   

    private transient AutowireCapableBeanFactory beanFactory;

    @Override
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
   
        final Object jobInstance = super.createJobInstance(bundle);
        beanFactory.autowireBean(jobInstance);
        return jobInstance;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
   
        this.beanFactory = applicationContext.getAutowireCapableBeanFactory();
    }

}

3、创建定时任务抽象类

public abstract class AbstractTask implements Job {
   

    private Logger logger = LoggerFactory.getLogger(AbstractTask.class);

    protected abstract void executeInternal(JobExecutionContext context) throws Exception;

    /**
     * 定时任务标识
     */
    private String key;

    /**
     * 数据库里配置的主键id
     */
    private Long dataBaseId;

    @Override
    public void execute(JobExecutionContext context) {
   
        try {
   
            executeInternal(context);
        } catch (Exception e) {
   
            logger.error(e.getMessage(), e);
            logger.error("job execute failed!");
        }
    }

    public String getKey() {
   
        return key;
    }

    public void setKey(String key) {
   
        this.key = key;
    }

    public Long getDataBaseId() {
   
        return dataBaseId;
    }

    public void setDataBaseId(Long dataBaseId) {
   
        this.dataBaseId = dataBaseId;
    }
}
  • 7
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 12
    评论
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值