下面一起來了解下如何實(shí)現(xiàn)SpringBoot+Quartz+Maven+MySQL動(dòng)態(tài)定時(shí)任務(wù),相信大家看完肯定會(huì)受益匪淺,文字在精不在多,希望如何實(shí)現(xiàn)SpringBoot+Quartz+Maven+MySql動(dòng)態(tài)定時(shí)任務(wù)這篇短內(nèi)容是你想要的。
創(chuàng)新互聯(lián)主營金昌網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營網(wǎng)站建設(shè)方案,成都app軟件開發(fā),金昌h5微信小程序搭建,金昌網(wǎng)站營銷推廣歡迎金昌等地區(qū)企業(yè)咨詢
1.Quartz需要導(dǎo)入的包,Maven配置
org.quartz-scheduler
quartz
2.2.3
org.quartz-scheduler
quartz-jobs
2.2.3
2.Quartz需要用到的表
DROP TABLE IF EXISTS qrtz_fired_triggers;
DROP TABLE IF EXISTS qrtz_paused_trigger_grps;
DROP TABLE IF EXISTS qrtz_scheduler_state;
DROP TABLE IF EXISTS qrtz_locks;
DROP TABLE IF EXISTS qrtz_simple_triggers;
DROP TABLE IF EXISTS qrtz_simprop_triggers;
DROP TABLE IF EXISTS qrtz_cron_triggers;
DROP TABLE IF EXISTS qrtz_blob_triggers;
DROP TABLE IF EXISTS qrtz_triggers;
DROP TABLE IF EXISTS qrtz_job_details;
DROP TABLE IF EXISTS qrtz_calendars;
#-- 存儲(chǔ)每一個(gè)已配置的 Job 的詳細(xì)信息
CREATE TABLE qrtz_job_details(
SCHED_NAME VARCHAR(120) NOT NULL,
JOB_NAME VARCHAR(200) NOT NULL,
JOB_GROUP VARCHAR(200) NOT NULL,
DESCRIPTION VARCHAR(250) NULL,
JOB_CLASS_NAME VARCHAR(250) NOT NULL,
IS_DURABLE VARCHAR(1) NOT NULL,
IS_NONCONCURRENT VARCHAR(1) NOT NULL,
IS_UPDATE_DATA VARCHAR(1) NOT NULL,
REQUESTS_RECOVERY VARCHAR(1) NOT NULL,
JOB_DATA BLOB NULL,
PRIMARY KEY (SCHED_NAME,JOB_NAME,JOB_GROUP)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
#--存儲(chǔ)已配置的 Trigger 的信息
CREATE TABLE qrtz_triggers (
SCHED_NAME VARCHAR(120) NOT NULL,
TRIGGER_NAME VARCHAR(200) NOT NULL,
TRIGGER_GROUP VARCHAR(200) NOT NULL,
JOB_NAME VARCHAR(200) NOT NULL,
JOB_GROUP VARCHAR(200) NOT NULL,
DESCRIPTION VARCHAR(250) NULL,
NEXT_FIRE_TIME BIGINT(13) NULL,
PREV_FIRE_TIME BIGINT(13) NULL,
PRIORITY INTEGER NULL,
TRIGGER_STATE VARCHAR(16) NOT NULL,
TRIGGER_TYPE VARCHAR(8) NOT NULL,
START_TIME BIGINT(13) NOT NULL,
END_TIME BIGINT(13) NULL,
CALENDAR_NAME VARCHAR(200) NULL,
MISFIRE_INSTR SMALLINT(2) NULL,
JOB_DATA BLOB NULL,
PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
FOREIGN KEY (SCHED_NAME,JOB_NAME,JOB_GROUP)
REFERENCES qrtz_job_details(SCHED_NAME,JOB_NAME,JOB_GROUP)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
#-- 存儲(chǔ)簡單的 Trigger,包括重復(fù)次數(shù),間隔,以及已觸的次數(shù)
CREATE TABLE qrtz_simple_triggers (
SCHED_NAME VARCHAR(120) NOT NULL,
TRIGGER_NAME VARCHAR(200) NOT NULL,
TRIGGER_GROUP VARCHAR(200) NOT NULL,
REPEAT_COUNT BIGINT(7) NOT NULL,
REPEAT_INTERVAL BIGINT(12) NOT NULL,
TIMES_TRIGGERED BIGINT(10) NOT NULL,
PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
REFERENCES qrtz_triggers(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
#-- 存儲(chǔ) Cron Trigger,包括 Cron 表達(dá)式和時(shí)區(qū)信息
CREATE TABLE qrtz_cron_triggers (
SCHED_NAME VARCHAR(120) NOT NULL,
TRIGGER_NAME VARCHAR(200) NOT NULL,
TRIGGER_GROUP VARCHAR(200) NOT NULL,
CRON_EXPRESSION VARCHAR(120) NOT NULL,
TIME_ZONE_ID VARCHAR(80),
PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
REFERENCES qrtz_triggers(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
#-- 存儲(chǔ)簡單的 Trigger,包括重復(fù)次數(shù),間隔,以及已觸的次數(shù)
CREATE TABLE qrtz_simprop_triggers (
SCHED_NAME VARCHAR(120) NOT NULL,
TRIGGER_NAME VARCHAR(200) NOT NULL,
TRIGGER_GROUP VARCHAR(200) NOT NULL,
STR_PROP_1 VARCHAR(512) NULL,
STR_PROP_2 VARCHAR(512) NULL,
STR_PROP_3 VARCHAR(512) NULL,
INT_PROP_1 INT NULL,
INT_PROP_2 INT NULL,
LONG_PROP_1 BIGINT NULL,
LONG_PROP_2 BIGINT NULL,
DEC_PROP_1 NUMERIC(13,4) NULL,
DEC_PROP_2 NUMERIC(13,4) NULL,
BOOL_PROP_1 VARCHAR(1) NULL,
BOOL_PROP_2 VARCHAR(1) NULL,
PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
REFERENCES qrtz_triggers(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
#-- Trigger 作為 Blob 類型存儲(chǔ)
#-- (用于 Quartz 用戶用 JDBC 創(chuàng)建他們自己定制的 Trigger 類型,JobStore并不知道如何存儲(chǔ)實(shí)例的時(shí)候)
CREATE TABLE qrtz_blob_triggers (
SCHED_NAME VARCHAR(120) NOT NULL,
TRIGGER_NAME VARCHAR(200) NOT NULL,
TRIGGER_GROUP VARCHAR(200) NOT NULL,
BLOB_DATA BLOB NULL,
PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
INDEX (SCHED_NAME,TRIGGER_NAME, TRIGGER_GROUP),
FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
REFERENCES qrtz_triggers(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
#-- 以 Blob 類型存儲(chǔ) Quartz 的 Calendar 信息
CREATE TABLE qrtz_calendars (
SCHED_NAME VARCHAR(120) NOT NULL,
CALENDAR_NAME VARCHAR(200) NOT NULL,
CALENDAR BLOB NOT NULL,
PRIMARY KEY (SCHED_NAME,CALENDAR_NAME)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
#-- 存儲(chǔ)已暫停的 Trigger 組的信息
CREATE TABLE qrtz_paused_trigger_grps (
SCHED_NAME VARCHAR(120) NOT NULL,
TRIGGER_GROUP VARCHAR(200) NOT NULL,
PRIMARY KEY (SCHED_NAME,TRIGGER_GROUP)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
#-- 存儲(chǔ)與已觸發(fā)的 Trigger 相關(guān)的狀態(tài)信息,以及相聯(lián) Job 的執(zhí)行信息
CREATE TABLE qrtz_fired_triggers (
SCHED_NAME VARCHAR(120) NOT NULL,
ENTRY_ID VARCHAR(95) NOT NULL,
TRIGGER_NAME VARCHAR(200) NOT NULL,
TRIGGER_GROUP VARCHAR(200) NOT NULL,
INSTANCE_NAME VARCHAR(200) NOT NULL,
FIRED_TIME BIGINT(13) NOT NULL,
SCHED_TIME BIGINT(13) NOT NULL,
PRIORITY INTEGER NOT NULL,
STATE VARCHAR(16) NOT NULL,
JOB_NAME VARCHAR(200) NULL,
JOB_GROUP VARCHAR(200) NULL,
IS_NONCONCURRENT VARCHAR(1) NULL,
REQUESTS_RECOVERY VARCHAR(1) NULL,
PRIMARY KEY (SCHED_NAME,ENTRY_ID)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
#-- 存儲(chǔ)少量的有關(guān) Scheduler 的狀態(tài)信息,和別的 Scheduler 實(shí)例(假如是用于一個(gè)集群中)
CREATE TABLE qrtz_scheduler_state (
SCHED_NAME VARCHAR(120) NOT NULL,
INSTANCE_NAME VARCHAR(200) NOT NULL,
LAST_CHECKIN_TIME BIGINT(13) NOT NULL,
CHECKIN_INTERVAL BIGINT(13) NOT NULL,
PRIMARY KEY (SCHED_NAME,INSTANCE_NAME)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
#-- 存儲(chǔ)程序的悲觀鎖的信息(假如使用了悲觀鎖)
CREATE TABLE qrtz_locks (
SCHED_NAME VARCHAR(120) NOT NULL,
LOCK_NAME VARCHAR(40) NOT NULL,
PRIMARY KEY (SCHED_NAME,LOCK_NAME)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
CREATE INDEX IDX_QRTZ_J_REQ_RECOVERY ON qrtz_job_details(SCHED_NAME,REQUESTS_RECOVERY);
CREATE INDEX IDX_QRTZ_J_GRP ON qrtz_job_details(SCHED_NAME,JOB_GROUP);
CREATE INDEX IDX_QRTZ_T_J ON qrtz_triggers(SCHED_NAME,JOB_NAME,JOB_GROUP);
CREATE INDEX IDX_QRTZ_T_JG ON qrtz_triggers(SCHED_NAME,JOB_GROUP);
CREATE INDEX IDX_QRTZ_T_C ON qrtz_triggers(SCHED_NAME,CALENDAR_NAME);
CREATE INDEX IDX_QRTZ_T_G ON qrtz_triggers(SCHED_NAME,TRIGGER_GROUP);
CREATE INDEX IDX_QRTZ_T_STATE ON qrtz_triggers(SCHED_NAME,TRIGGER_STATE);
CREATE INDEX IDX_QRTZ_T_N_STATE ON qrtz_triggers(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP,TRIGGER_STATE);
CREATE INDEX IDX_QRTZ_T_N_G_STATE ON qrtz_triggers(SCHED_NAME,TRIGGER_GROUP,TRIGGER_STATE);
CREATE INDEX IDX_QRTZ_T_NEXT_FIRE_TIME ON qrtz_triggers(SCHED_NAME,NEXT_FIRE_TIME);
CREATE INDEX IDX_QRTZ_T_NFT_ST ON qrtz_triggers(SCHED_NAME,TRIGGER_STATE,NEXT_FIRE_TIME);
CREATE INDEX IDX_QRTZ_T_NFT_MISFIRE ON qrtz_triggers(SCHED_NAME,MISFIRE_INSTR,NEXT_FIRE_TIME);
CREATE INDEX IDX_QRTZ_T_NFT_ST_MISFIRE ON qrtz_triggers(SCHED_NAME,MISFIRE_INSTR,NEXT_FIRE_TIME,TRIGGER_STATE);
CREATE INDEX IDX_QRTZ_T_NFT_ST_MISFIRE_GRP ON qrtz_triggers(SCHED_NAME,MISFIRE_INSTR,NEXT_FIRE_TIME,TRIGGER_GROUP,TRIGGER_STATE);
CREATE INDEX IDX_QRTZ_FT_TRIG_INST_NAME ON qrtz_fired_triggers(SCHED_NAME,INSTANCE_NAME);
CREATE INDEX IDX_QRTZ_FT_INST_JOB_REQ_RCVRY ON qrtz_fired_triggers(SCHED_NAME,INSTANCE_NAME,REQUESTS_RECOVERY);
CREATE INDEX IDX_QRTZ_FT_J_G ON qrtz_fired_triggers(SCHED_NAME,JOB_NAME,JOB_GROUP);
CREATE INDEX IDX_QRTZ_FT_JG ON qrtz_fired_triggers(SCHED_NAME,JOB_GROUP);
CREATE INDEX IDX_QRTZ_FT_T_G ON qrtz_fired_triggers(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP);
CREATE INDEX IDX_QRTZ_FT_TG ON qrtz_fired_triggers(SCHED_NAME,TRIGGER_GROUP);
commit;
3.Quartz需要用到的配置(quartz.properties)
#quartz集群配置
# ===========================================================================
# Configure Main Scheduler Properties 調(diào)度器屬性
# ===========================================================================
#調(diào)度標(biāo)識名 集群中每一個(gè)實(shí)例都必須使用相同的名稱
org.quartz.scheduler.instanceName=DefaultQuartzScheduler
#ID設(shè)置為自動(dòng)獲取 每一個(gè)必須不同
org.quartz.scheduler.instanceid=AUTO
#============================================================================
# Configure ThreadPool
#============================================================================
#線程池的實(shí)現(xiàn)類(一般使用SimpleThreadPool即可滿足幾乎所有用戶的需求)
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
#指定線程數(shù),至少為1(無默認(rèn)值)(一般設(shè)置為1-100直接的整數(shù)合適)
org.quartz.threadPool.threadCount = 25
#設(shè)置線程的優(yōu)先級(最大為java.lang.Thread.MAX_PRIORITY 10,最小為Thread.MIN_PRIORITY 1,默認(rèn)為5)
org.quartz.threadPool.threadPriority = 5
#============================================================================
# Configure JobStore
#============================================================================
# 信息保存時(shí)間 默認(rèn)值60秒
org.quartz.jobStore.misfireThreshold = 60000
#數(shù)據(jù)保存方式為數(shù)據(jù)庫持久化
org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
#數(shù)據(jù)庫代理類,一般org.quartz.impl.jdbcjobstore.StdJDBCDelegate可以滿足大部分?jǐn)?shù)據(jù)庫
org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate
#JobDataMaps是否都為String類型
org.quartz.jobStore.useProperties = false
#數(shù)據(jù)庫別名 隨便取
org.quartz.jobStore.dataSource = myDS
#表的前綴,默認(rèn)QRTZ_
org.quartz.jobStore.tablePrefix = QRTZ_
#是否加入集群
org.quartz.jobStore.isClustered = true
#調(diào)度實(shí)例失效的檢查時(shí)間間隔
org.quartz.jobStore.clusterCheckinInterval = 20000
#============================================================================
# Configure Datasources
#============================================================================
#數(shù)據(jù)庫引擎
org.quartz.dataSource.myDS.driver = com.mysql.jdbc.Driver
#數(shù)據(jù)庫連接
org.quartz.dataSource.myDS.URL = jdbc:mysql://localhost:3306/testdb?characterEncoding=utf8&allowMultiQueries=true&useSSL=false&autoReconnect=true
#數(shù)據(jù)庫用戶
org.quartz.dataSource.myDS.user = root
#數(shù)據(jù)庫密碼
org.quartz.dataSource.myDS.password = root
#允許最大連接
org.quartz.dataSource.myDS.maxConnections = 5
#驗(yàn)證查詢sql,可以不設(shè)置
org.quartz.dataSource.myDS.validationQuery=select 0 from dual
4.Quartz任務(wù)工廠類(TaskJobFactory)
@Component
public class TaskJobFactory extends AdaptableJobFactory {
@Autowired
AutowireCapableBeanFactory capableBeanFactory;
@Override
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
//調(diào)用父類的方法
Object jobInstance = super.createJobInstance(bundle);
//進(jìn)行注入
capableBeanFactory.autowireBean(jobInstance);
return jobInstance;
}
}
5.Quartz配置類(QuartzConfigurer)
@Configuration
public class QuartzConfigurer {
@Autowired
DataSource dataSource;
@Autowired
TaskJobFactory jobFactory;
@Bean(name = "SchedulerFactory")
public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
//獲取配置屬性
PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
//在quartz.properties中的屬性被讀取并注入后再初始化對象
propertiesFactoryBean.afterPropertiesSet();
//創(chuàng)建SchedulerFactoryBean
SchedulerFactoryBean factory = new SchedulerFactoryBean();
factory.setQuartzProperties(propertiesFactoryBean.getObject());
factory.setJobFactory(jobFactory);
return factory;
}
/*
* 通過SchedulerFactoryBean獲取Scheduler的實(shí)例
*/
@Bean(name = "scheduler")
public Scheduler scheduler() throws IOException {
return schedulerFactoryBean().getScheduler();
}
}
6.Quartz操作類(QuartzJobManager)
@Component
public class QuartzJobManager {
private static final Logger logger = LoggerFactory.getLogger(QuartzJobManager.class);
private static QuartzJobManager jobUtil;
@Autowired
private Scheduler scheduler;
public QuartzJobManager() {
logger.info("init jobUtil");
jobUtil = this;
}
public static QuartzJobManager getInstance() {
logger.info("return JobCreateUtil");
return QuartzJobManager.jobUtil;
}
/**
* 創(chuàng)建job
*
* @param clazz 任務(wù)類
* @param jobName 任務(wù)名稱
* @param jobGroupName 任務(wù)所在組名稱
* @param cronExpression cron表達(dá)式
*/
public void addJob(Class clazz, String jobName, String jobGroupName, String cronExpression) {
addJob(clazz, jobName, jobGroupName, cronExpression, null);
}
/**
* 創(chuàng)建job,可傳參
*
* @param clazz 任務(wù)類
* @param jobName 任務(wù)名稱
* @param jobGroupName 任務(wù)所在組名稱
* @param cronExpression cron表達(dá)式
* @param argMap map形式參數(shù)
*/
public void addJob(Class clazz, String jobName, String jobGroupName, String cronExpression, Map argMap) {
try {
// 啟動(dòng)調(diào)度器
scheduler.start();
//構(gòu)建job信息
JobDetail jobDetail = JobBuilder.newJob(((Job) clazz.newInstance()).getClass()).withIdentity(jobName, jobGroupName).build();
//表達(dá)式調(diào)度構(gòu)建器(即任務(wù)執(zhí)行的時(shí)間)
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
//按新的cronExpression表達(dá)式構(gòu)建一個(gè)新的trigger
CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(jobName, jobGroupName).withSchedule(scheduleBuilder).build();
//獲得JobDataMap,寫入數(shù)據(jù)
if (argMap != null) {
trigger.getJobDataMap().putAll(argMap);
}
scheduler.scheduleJob(jobDetail, trigger);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 暫停job
*
* @param jobName 任務(wù)名稱
* @param jobGroupName 任務(wù)所在組名稱
*/
public void pauseJob(String jobName, String jobGroupName) {
try {
scheduler.pauseJob(JobKey.jobKey(jobName, jobGroupName));
} catch (SchedulerException e) {
e.printStackTrace();
}
}
/**
* 恢復(fù)job
*
* @param jobName 任務(wù)名稱
* @param jobGroupName 任務(wù)所在組名稱
*/
public void resumeJob(String jobName, String jobGroupName) {
try {
scheduler.resumeJob(JobKey.jobKey(jobName, jobGroupName));
} catch (SchedulerException e) {
e.printStackTrace();
}
}
/**
* job 更新,只更新頻率
*
* @param jobName 任務(wù)名稱
* @param jobGroupName 任務(wù)所在組名稱
* @param cronExpression cron表達(dá)式
*/
public void updateJob(String jobName, String jobGroupName, String cronExpression) {
updateJob(jobName, jobGroupName, cronExpression, null);
}
/**
* job 更新,更新頻率和參數(shù)
*
* @param jobName 任務(wù)名稱
* @param jobGroupName 任務(wù)所在組名稱
* @param cronExpression cron表達(dá)式
* @param argMap 參數(shù)
*/
public void updateJob(String jobName, String jobGroupName, String cronExpression, Map argMap) {
try {
TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroupName);
// 表達(dá)式調(diào)度構(gòu)建器
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
// 按新的cronExpression表達(dá)式重新構(gòu)建trigger
trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
//修改map
if (argMap != null) {
trigger.getJobDataMap().putAll(argMap);
}無錫×××醫(yī)院 http://www.bhnkyixue.com/
// 按新的trigger重新設(shè)置job執(zhí)行
scheduler.rescheduleJob(triggerKey, trigger);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* job 更新,只更新更新參數(shù)
*
* @param jobName 任務(wù)名稱
* @param jobGroupName 任務(wù)所在組名稱
* @param argMap 參數(shù)
*/
public void updateJob(String jobName, String jobGroupName, Map argMap) {
try {
TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroupName);
CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
//修改map
trigger.getJobDataMap().putAll(argMap);
// 按新的trigger重新設(shè)置job執(zhí)行
scheduler.rescheduleJob(triggerKey, trigger);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* job 刪除
*
* @param jobName 任務(wù)名稱
* @param jobGroupName 任務(wù)所在組名稱
*/
public void deleteJob(String jobName, String jobGroupName) {
try {
scheduler.pauseTrigger(TriggerKey.triggerKey(jobName, jobGroupName));
scheduler.unscheduleJob(TriggerKey.triggerKey(jobName, jobGroupName));
scheduler.deleteJob(JobKey.jobKey(jobName, jobGroupName));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 啟動(dòng)所有定時(shí)任務(wù)
*/
public void startAllJobs() {
try {
scheduler.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 關(guān)閉所有定時(shí)任務(wù)
*/
public void shutdownAllJobs() {
try {
if (!scheduler.isShutdown()) {
scheduler.shutdown();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 獲取所有任務(wù)列表
*
* @return
*/
public List> getAllJob() {
GroupMatcher matcher = GroupMatcher.anyJobGroup();
List> jobList = new ArrayList<>();
Set jobKeys = null;
try {
jobKeys = scheduler.getJobKeys(matcher);
for (JobKey jobKey : jobKeys) {
List triggers = scheduler.getTriggersOfJob(jobKey);
for (Trigger trigger : triggers) {
Map job = new HashMap<>();
job.put("jobName", jobKey.getName());
job.put("jobGroupName", jobKey.getGroup());
job.put("trigger", trigger.getKey());
Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
job.put("jobStatus", triggerState.name());
if (trigger instanceof CronTrigger) {
CronTrigger cronTrigger = (CronTrigger) trigger;
String cronExpression = cronTrigger.getCronExpression();
job.put("cronExpression", cronExpression);
}
jobList.add(job);
}
}
} catch (SchedulerException e) {
e.printStackTrace();
}
return jobList;
}
}
7.測試類(TestQuartz)
@Component
public class TestQuartz implements Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
//獲取任務(wù)名
String taskName = context.getJobDetail().getKey().getName();
//處理執(zhí)行任務(wù)之后的業(yè)務(wù)
}
}
8.測試類(JobController)
@Controller
@RequestMapping("/job")
public class JobController {
@Autowired
QuartzJobManager quartzJobManager;
@GetMapping("/add")
public void add(HttpServletRequest request) {
//任務(wù)名稱
String name = request.getParameter("name");
//任務(wù)組名稱
String groupName = "task";
//cron表達(dá)式
String cron = "0 0/1 * * * ?";
//需要給任務(wù)攜帶的參數(shù)
Map map = new HashMap<>();
map.put("name", "張三");
map.put("sex", "0");
quartzJobManager.addJob(TestQuartz.class, name, groupName, cron, map);
}
@GetMapping("/del")
public void del(HttpServletRequest request) {
String name = request.getParameter("name");
String groupName = "task";
quartzJobManager.deleteJob(name, groupName);
}
}
這是一個(gè)Quartz動(dòng)態(tài)任務(wù)需要的所有源碼,測試?yán)锩嬷粚懥?個(gè),其他的可以自己去測試,一個(gè)簡單的Quartz的測試案例就搭建好了,你也可以直接在這個(gè)基礎(chǔ)上結(jié)合項(xiàng)目的業(yè)務(wù)場景去擴(kuò)展。
看完如何實(shí)現(xiàn)SpringBoot+Quartz+Maven+MySql動(dòng)態(tài)定時(shí)任務(wù)這篇文章后,很多讀者朋友肯定會(huì)想要了解更多的相關(guān)內(nèi)容,如需獲取更多的行業(yè)信息,可以關(guān)注我們的行業(yè)資訊欄目。
標(biāo)題名稱:如何實(shí)現(xiàn)SpringBoot+Quartz+Maven+MySql動(dòng)態(tài)定時(shí)任務(wù)
文章起源:http://jinyejixie.com/article14/iisege.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站排名、定制開發(fā)、品牌網(wǎng)站設(shè)計(jì)、用戶體驗(yàn)、營銷型網(wǎng)站建設(shè)、服務(wù)器托管
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)