Spring Boot集成Quartz-动态任务管理

本文介绍了如何在Spring Boot中集成Quartz进行动态任务管理,包括新建、更新、删除、暂停和恢复任务的操作。同时,文章讨论了在实际开发中遇到的初始化调度器、Bean注入、保存执行记录、监听器中注入业务Bean以及Job并发等问题,并提供了相应的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Quartz提供了一组丰富的API,来管理Job。

前言

当定时任务越来越多时,集中管理Job越有必要。Quartz提供了一组丰富的API,来管理Job。

Spring Boot 定时任务之Quartz中讲了Spring Boot怎么集成quartz,这里结合实际业务,参考网上一些经验,总结一下集成的一些坑。

动态任务管理

下面以官方的例子来说明一下这些常用的API。

定义Job实现类

public class ColorJob implements Job {
   
   

    public ColorJob() {
        // Instances of Job must have a public no-argument constructor.
    }

    public void execute(JobExecutionContext context)
            throws JobExecutionException {

        JobDataMap data = context.getMergedJobDataMap();
        System.out.println("someProp = " + data.getString("someProp"));
    }

}

定义JobDetailTrigger

// Define job instance
JobDetail job1 = newJob(ColorJob.class)
    .withIdentity("job1", "group1")
    .build();

// Define a Trigger that will fire "now", and not repeat
Trigger trigger1 = newTrigger()
    .withIdentity("trigger1", "group1")
    .startNow()
    .build();

新建

把Job添加到调度器sched中。

// Add the the job to the scheduler's store
sched.add(job1, trigger1);

更新

TriggerKey triggerKey = TriggerKey.triggerKey("job1", "group1");
// store, and set overwrite flag to 'true'  
scheduler.addJob(job1, true);
// tell the scheduler to remove the old trigger with the given key, and put the new one in its place
scheduler.rescheduleJob(triggerKey, trigger1);

删除

JobKey jobKey = JobKey.jobKey("job1", "group1");
scheduler.deleteJob(jobKey);

暂停

JobKey jobKey = JobKey.jobKey("job1", "group1");
scheduler.pauseJob(jobKey);

恢复

JobKey jobKey = JobKey.jobKey("job1", "group1");
scheduler.resumeJob(jobKey);

立即执行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

无心水

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值