当前位置:   article > 正文

SpringBoot 整合 Quartz_springboot整合quartz

springboot整合quartz
  1. 先说为什么会用Quartz吧, 业务需求是在一个时间段比如 12:00---16:00,开始前一个小时需要提醒一次用户,结束前一个小时需要用户,12:00整的时候也需要提醒一次用户,并且可能多个存在多个这样相同的任务.(所以就需要一个任务时间不会错乱的,timertask可能会导致任务时间错乱,所以首先就排除,quartz每一个任务都是一个新的线程,因为使用到了线程池+时间轮),整合如下:

1.导入依赖

  1. <!--spring与quartz依赖-->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-quartz</artifactId>
  5. <version>2.6.6</version>
  6. </dependency>
  1. 因为这里我选择了把任务持久化到数据库,防止宕机过后任务丢失(记得更换自己的数据库账号密码)

  1. #调度配置
  2. #调度器实例名称
  3. org.quartz.scheduler.instanceName=SsmScheduler
  4. #调度器实例编号自动生成
  5. org.quartz.scheduler.instanceId=AUTO
  6. #是否在Quartz执行一个job前使用UserTransaction
  7. org.quartz.scheduler.wrapJobExecutionInUserTransaction=false
  8. #线程池配置
  9. #线程池的实现类
  10. org.quartz.threadPool.class=org.quartz.simpl.SimpleThreadPool
  11. #线程池中的线程数量
  12. org.quartz.threadPool.threadCount=10
  13. #线程优先级
  14. org.quartz.threadPool.threadPriority=5
  15. #配置是否启动自动加载数据库内的定时任务,默认true
  16. org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread=true
  17. #是否设置为守护线程,设置后任务将不会执行
  18. #org.quartz.threadPool.makeThreadsDaemons=true
  19. #持久化方式配置
  20. #JobDataMaps是否都为String类型
  21. org.quartz.jobStore.useProperties=true
  22. #数据表的前缀,默认QRTZ_
  23. org.quartz.jobStore.tablePrefix=qrtz_
  24. #最大能忍受的触发超时时间
  25. org.quartz.jobStore.misfireThreshold=60000
  26. #是否以集群方式运行
  27. org.quartz.jobStore.isClustered=true
  28. #调度实例失效的检查时间间隔,单位毫秒
  29. org.quartz.jobStore.clusterCheckinInterval=2000
  30. #数据保存方式为数据库持久化
  31. org.quartz.jobStore.class=org.quartz.impl.jdbcjobstore.JobStoreTX
  32. #数据库代理类,一般org.quartz.impl.jdbcjobstore.StdJDBCDelegate可以满足大部分数据库
  33. org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.StdJDBCDelegate
  34. #数据库别名 随便取
  35. org.quartz.jobStore.dataSource=qzDS
  36. #数据库连接池,将其设置为druid
  37. org.quartz.dataSource.qzDS.connectionProvider.class=com.ruoyi.system.config.DruidConnectionProvider
  38. #数据库引擎
  39. org.quartz.dataSource.qzDS.driver=com.mysql.cj.jdbc.Driver
  40. #数据库连接
  41. org.quartz.dataSource.qzDS.URL=jdbc:mysql://127.0.0.1:3306/ry-cloud?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
  42. #数据库用户
  43. org.quartz.dataSource.qzDS.user=root
  44. #数据库密码
  45. org.quartz.dataSource.qzDS.password=abc123
  46. #允许最大连接
  47. org.quartz.dataSource.qzDS.maxConnection=5
  48. #验证查询sql,可以不设置
  49. #org.quartz.dataSource.qzDS.validationQuery=select 0 from dual
  50. #数据库连接池,将其设置为druid

添加数据库表,这里官方已经提供了sql文件,官方网站:http://quartz-scheduler.org/

路径:quartz-2.3.0-SNAPSHOT\src\org\quartz\impl\jdbcjobstore\tables_mysql_innodb.sql

  1. #
  2. # In your Quartz properties file, you'll need to set
  3. # org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate
  4. #
  5. #
  6. # By: Ron Cordell - roncordell
  7. # I didn't see this anywhere, so I thought I'd post it here. This is the script from Quartz to create the tables in a MySQL database, modified to use INNODB instead of MYISAM.
  8. DROP TABLE IF EXISTS QRTZ_FIRED_TRIGGERS;
  9. DROP TABLE IF EXISTS QRTZ_PAUSED_TRIGGER_GRPS;
  10. DROP TABLE IF EXISTS QRTZ_SCHEDULER_STATE;
  11. DROP TABLE IF EXISTS QRTZ_LOCKS;
  12. DROP TABLE IF EXISTS QRTZ_SIMPLE_TRIGGERS;
  13. DROP TABLE IF EXISTS QRTZ_SIMPROP_TRIGGERS;
  14. DROP TABLE IF EXISTS QRTZ_CRON_TRIGGERS;
  15. DROP TABLE IF EXISTS QRTZ_BLOB_TRIGGERS;
  16. DROP TABLE IF EXISTS QRTZ_TRIGGERS;
  17. DROP TABLE IF EXISTS QRTZ_JOB_DETAILS;
  18. DROP TABLE IF EXISTS QRTZ_CALENDARS;
  19. CREATE TABLE QRTZ_JOB_DETAILS(
  20. SCHED_NAME VARCHAR(120) NOT NULL,
  21. JOB_NAME VARCHAR(190) NOT NULL,
  22. JOB_GROUP VARCHAR(190) NOT NULL,
  23. DESCRIPTION VARCHAR(250) NULL,
  24. JOB_CLASS_NAME VARCHAR(250) NOT NULL,
  25. IS_DURABLE VARCHAR(1) NOT NULL,
  26. IS_NONCONCURRENT VARCHAR(1) NOT NULL,
  27. IS_UPDATE_DATA VARCHAR(1) NOT NULL,
  28. REQUESTS_RECOVERY VARCHAR(1) NOT NULL,
  29. JOB_DATA BLOB NULL,
  30. PRIMARY KEY (SCHED_NAME,JOB_NAME,JOB_GROUP))
  31. ENGINE=InnoDB;
  32. CREATE TABLE QRTZ_TRIGGERS (
  33. SCHED_NAME VARCHAR(120) NOT NULL,
  34. TRIGGER_NAME VARCHAR(190) NOT NULL,
  35. TRIGGER_GROUP VARCHAR(190) NOT NULL,
  36. JOB_NAME VARCHAR(190) NOT NULL,
  37. JOB_GROUP VARCHAR(190) NOT NULL,
  38. DESCRIPTION VARCHAR(250) NULL,
  39. NEXT_FIRE_TIME BIGINT(13) NULL,
  40. PREV_FIRE_TIME BIGINT(13) NULL,
  41. PRIORITY INTEGER NULL,
  42. TRIGGER_STATE VARCHAR(16) NOT NULL,
  43. TRIGGER_TYPE VARCHAR(8) NOT NULL,
  44. START_TIME BIGINT(13) NOT NULL,
  45. END_TIME BIGINT(13) NULL,
  46. CALENDAR_NAME VARCHAR(190) NULL,
  47. MISFIRE_INSTR SMALLINT(2) NULL,
  48. JOB_DATA BLOB NULL,
  49. PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
  50. FOREIGN KEY (SCHED_NAME,JOB_NAME,JOB_GROUP)
  51. REFERENCES QRTZ_JOB_DETAILS(SCHED_NAME,JOB_NAME,JOB_GROUP))
  52. ENGINE=InnoDB;
  53. CREATE TABLE QRTZ_SIMPLE_TRIGGERS (
  54. SCHED_NAME VARCHAR(120) NOT NULL,
  55. TRIGGER_NAME VARCHAR(190) NOT NULL,
  56. TRIGGER_GROUP VARCHAR(190) NOT NULL,
  57. REPEAT_COUNT BIGINT(7) NOT NULL,
  58. REPEAT_INTERVAL BIGINT(12) NOT NULL,
  59. TIMES_TRIGGERED BIGINT(10) NOT NULL,
  60. PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
  61. FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
  62. REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP))
  63. ENGINE=InnoDB;
  64. CREATE TABLE QRTZ_CRON_TRIGGERS (
  65. SCHED_NAME VARCHAR(120) NOT NULL,
  66. TRIGGER_NAME VARCHAR(190) NOT NULL,
  67. TRIGGER_GROUP VARCHAR(190) NOT NULL,
  68. CRON_EXPRESSION VARCHAR(120) NOT NULL,
  69. TIME_ZONE_ID VARCHAR(80),
  70. PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
  71. FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
  72. REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP))
  73. ENGINE=InnoDB;
  74. CREATE TABLE QRTZ_SIMPROP_TRIGGERS
  75. (
  76. SCHED_NAME VARCHAR(120) NOT NULL,
  77. TRIGGER_NAME VARCHAR(190) NOT NULL,
  78. TRIGGER_GROUP VARCHAR(190) NOT NULL,
  79. STR_PROP_1 VARCHAR(512) NULL,
  80. STR_PROP_2 VARCHAR(512) NULL,
  81. STR_PROP_3 VARCHAR(512) NULL,
  82. INT_PROP_1 INT NULL,
  83. INT_PROP_2 INT NULL,
  84. LONG_PROP_1 BIGINT NULL,
  85. LONG_PROP_2 BIGINT NULL,
  86. DEC_PROP_1 NUMERIC(13,4) NULL,
  87. DEC_PROP_2 NUMERIC(13,4) NULL,
  88. BOOL_PROP_1 VARCHAR(1) NULL,
  89. BOOL_PROP_2 VARCHAR(1) NULL,
  90. PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
  91. FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
  92. REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP))
  93. ENGINE=InnoDB;
  94. CREATE TABLE QRTZ_BLOB_TRIGGERS (
  95. SCHED_NAME VARCHAR(120) NOT NULL,
  96. TRIGGER_NAME VARCHAR(190) NOT NULL,
  97. TRIGGER_GROUP VARCHAR(190) NOT NULL,
  98. BLOB_DATA BLOB NULL,
  99. PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
  100. INDEX (SCHED_NAME,TRIGGER_NAME, TRIGGER_GROUP),
  101. FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
  102. REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP))
  103. ENGINE=InnoDB;
  104. CREATE TABLE QRTZ_CALENDARS (
  105. SCHED_NAME VARCHAR(120) NOT NULL,
  106. CALENDAR_NAME VARCHAR(190) NOT NULL,
  107. CALENDAR BLOB NOT NULL,
  108. PRIMARY KEY (SCHED_NAME,CALENDAR_NAME))
  109. ENGINE=InnoDB;
  110. CREATE TABLE QRTZ_PAUSED_TRIGGER_GRPS (
  111. SCHED_NAME VARCHAR(120) NOT NULL,
  112. TRIGGER_GROUP VARCHAR(190) NOT NULL,
  113. PRIMARY KEY (SCHED_NAME,TRIGGER_GROUP))
  114. ENGINE=InnoDB;
  115. CREATE TABLE QRTZ_FIRED_TRIGGERS (
  116. SCHED_NAME VARCHAR(120) NOT NULL,
  117. ENTRY_ID VARCHAR(95) NOT NULL,
  118. TRIGGER_NAME VARCHAR(190) NOT NULL,
  119. TRIGGER_GROUP VARCHAR(190) NOT NULL,
  120. INSTANCE_NAME VARCHAR(190) NOT NULL,
  121. FIRED_TIME BIGINT(13) NOT NULL,
  122. SCHED_TIME BIGINT(13) NOT NULL,
  123. PRIORITY INTEGER NOT NULL,
  124. STATE VARCHAR(16) NOT NULL,
  125. JOB_NAME VARCHAR(190) NULL,
  126. JOB_GROUP VARCHAR(190) NULL,
  127. IS_NONCONCURRENT VARCHAR(1) NULL,
  128. REQUESTS_RECOVERY VARCHAR(1) NULL,
  129. PRIMARY KEY (SCHED_NAME,ENTRY_ID))
  130. ENGINE=InnoDB;
  131. CREATE TABLE QRTZ_SCHEDULER_STATE (
  132. SCHED_NAME VARCHAR(120) NOT NULL,
  133. INSTANCE_NAME VARCHAR(190) NOT NULL,
  134. LAST_CHECKIN_TIME BIGINT(13) NOT NULL,
  135. CHECKIN_INTERVAL BIGINT(13) NOT NULL,
  136. PRIMARY KEY (SCHED_NAME,INSTANCE_NAME))
  137. ENGINE=InnoDB;
  138. CREATE TABLE QRTZ_LOCKS (
  139. SCHED_NAME VARCHAR(120) NOT NULL,
  140. LOCK_NAME VARCHAR(40) NOT NULL,
  141. PRIMARY KEY (SCHED_NAME,LOCK_NAME))
  142. ENGINE=InnoDB;
  143. CREATE INDEX IDX_QRTZ_J_REQ_RECOVERY ON QRTZ_JOB_DETAILS(SCHED_NAME,REQUESTS_RECOVERY);
  144. CREATE INDEX IDX_QRTZ_J_GRP ON QRTZ_JOB_DETAILS(SCHED_NAME,JOB_GROUP);
  145. CREATE INDEX IDX_QRTZ_T_J ON QRTZ_TRIGGERS(SCHED_NAME,JOB_NAME,JOB_GROUP);
  146. CREATE INDEX IDX_QRTZ_T_JG ON QRTZ_TRIGGERS(SCHED_NAME,JOB_GROUP);
  147. CREATE INDEX IDX_QRTZ_T_C ON QRTZ_TRIGGERS(SCHED_NAME,CALENDAR_NAME);
  148. CREATE INDEX IDX_QRTZ_T_G ON QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_GROUP);
  149. CREATE INDEX IDX_QRTZ_T_STATE ON QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_STATE);
  150. CREATE INDEX IDX_QRTZ_T_N_STATE ON QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP,TRIGGER_STATE);
  151. CREATE INDEX IDX_QRTZ_T_N_G_STATE ON QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_GROUP,TRIGGER_STATE);
  152. CREATE INDEX IDX_QRTZ_T_NEXT_FIRE_TIME ON QRTZ_TRIGGERS(SCHED_NAME,NEXT_FIRE_TIME);
  153. CREATE INDEX IDX_QRTZ_T_NFT_ST ON QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_STATE,NEXT_FIRE_TIME);
  154. CREATE INDEX IDX_QRTZ_T_NFT_MISFIRE ON QRTZ_TRIGGERS(SCHED_NAME,MISFIRE_INSTR,NEXT_FIRE_TIME);
  155. CREATE INDEX IDX_QRTZ_T_NFT_ST_MISFIRE ON QRTZ_TRIGGERS(SCHED_NAME,MISFIRE_INSTR,NEXT_FIRE_TIME,TRIGGER_STATE);
  156. CREATE INDEX IDX_QRTZ_T_NFT_ST_MISFIRE_GRP ON QRTZ_TRIGGERS(SCHED_NAME,MISFIRE_INSTR,NEXT_FIRE_TIME,TRIGGER_GROUP,TRIGGER_STATE);
  157. CREATE INDEX IDX_QRTZ_FT_TRIG_INST_NAME ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,INSTANCE_NAME);
  158. CREATE INDEX IDX_QRTZ_FT_INST_JOB_REQ_RCVRY ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,INSTANCE_NAME,REQUESTS_RECOVERY);
  159. CREATE INDEX IDX_QRTZ_FT_J_G ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,JOB_NAME,JOB_GROUP);
  160. CREATE INDEX IDX_QRTZ_FT_JG ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,JOB_GROUP);
  161. CREATE INDEX IDX_QRTZ_FT_T_G ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP);
  162. CREATE INDEX IDX_QRTZ_FT_TG ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,TRIGGER_GROUP);
  163. commit;

配置连接池(需要导入druid依赖,上面忘了说),

  1. import com.alibaba.druid.pool.DruidDataSource;
  2. import com.alibaba.druid.pool.DruidPooledConnection;
  3. import org.quartz.SchedulerException;
  4. import org.quartz.utils.ConnectionProvider;
  5. import java.sql.SQLException;
  6. public class DruidConnectionProvider implements ConnectionProvider {
  7. /**
  8. * 常量配置,与quartz.properties文件的key保持一致(去掉前缀),同时提供set方法,Quartz框架自动注入值。
  9. * @return
  10. * @throws SQLException
  11. */
  12. //JDBC驱动
  13. public String driver;
  14. //JDBC连接串
  15. public String URL;
  16. //数据库用户名
  17. public String user;
  18. //数据库用户密码
  19. public String password;
  20. //数据库最大连接数
  21. public int maxConnection;
  22. //数据库SQL查询每次连接返回执行到连接池,以确保它仍然是有效的。
  23. public String validationQuery;
  24. private boolean validateOnCheckout;
  25. private int idleConnectionValidationSeconds;
  26. public String maxCachedStatementsPerConnection;
  27. private String discardIdleConnectionsSeconds;
  28. public static final int DEFAULT_DB_MAX_CONNECTIONS = 10;
  29. public static final int DEFAULT_DB_MAX_CACHED_STATEMENTS_PER_CONNECTION = 120;
  30. //Druid连接池
  31. private DruidDataSource datasource;
  32. @Override
  33. public DruidPooledConnection getConnection() throws SQLException {
  34. return datasource.getConnection();
  35. }
  36. @Override
  37. public void shutdown() throws SQLException {
  38. datasource.close();
  39. }
  40. @Override
  41. public void initialize() throws SQLException {
  42. if (this.URL == null) {
  43. throw new SQLException("DBPool could not be created: DB URL cannot be null");
  44. }
  45. if (this.driver == null) {
  46. throw new SQLException("DBPool driver could not be created: DB driver class name cannot be null!");
  47. }
  48. if (this.maxConnection < 0) {
  49. throw new SQLException("DBPool maxConnectins could not be created: Max connections must be greater than zero!");
  50. }
  51. datasource = new DruidDataSource();
  52. try{
  53. datasource.setDriverClassName(this.driver);
  54. } catch (Exception e) {
  55. try {
  56. throw new SchedulerException("Problem setting driver class name on datasource: " + e.getMessage(), e);
  57. } catch (SchedulerException e1) {
  58. }
  59. }
  60. datasource.setUrl(this.URL);
  61. datasource.setUsername(this.user);
  62. datasource.setPassword(this.password);
  63. datasource.setMaxActive(this.maxConnection);
  64. datasource.setMinIdle(1);
  65. datasource.setMaxWait(0);
  66. datasource.setMaxPoolPreparedStatementPerConnectionSize(DEFAULT_DB_MAX_CONNECTIONS);
  67. if (this.validationQuery != null) {
  68. datasource.setValidationQuery(this.validationQuery);
  69. if(!this.validateOnCheckout)
  70. datasource.setTestOnReturn(true);
  71. else
  72. datasource.setTestOnBorrow(true);
  73. datasource.setValidationQueryTimeout(this.idleConnectionValidationSeconds);
  74. }
  75. }
  76. public String getDriver() {
  77. return driver;
  78. }
  79. public void setDriver(String driver) {
  80. this.driver = driver;
  81. }
  82. public String getURL() {
  83. return URL;
  84. }
  85. public void setURL(String URL) {
  86. this.URL = URL;
  87. }
  88. public String getUser() {
  89. return user;
  90. }
  91. public void setUser(String user) {
  92. this.user = user;
  93. }
  94. public String getPassword() {
  95. return password;
  96. }
  97. public void setPassword(String password) {
  98. this.password = password;
  99. }
  100. public int getMaxConnection() {
  101. return maxConnection;
  102. }
  103. public void setMaxConnection(int maxConnection) {
  104. this.maxConnection = maxConnection;
  105. }
  106. public String getValidationQuery() {
  107. return validationQuery;
  108. }
  109. public void setValidationQuery(String validationQuery) {
  110. this.validationQuery = validationQuery;
  111. }
  112. public boolean isValidateOnCheckout() {
  113. return validateOnCheckout;
  114. }
  115. public void setValidateOnCheckout(boolean validateOnCheckout) {
  116. this.validateOnCheckout = validateOnCheckout;
  117. }
  118. public int getIdleConnectionValidationSeconds() {
  119. return idleConnectionValidationSeconds;
  120. }
  121. public void setIdleConnectionValidationSeconds(int idleConnectionValidationSeconds) {
  122. this.idleConnectionValidationSeconds = idleConnectionValidationSeconds;
  123. }
  124. public DruidDataSource getDatasource() {
  125. return datasource;
  126. }
  127. public void setDatasource(DruidDataSource datasource) {
  128. this.datasource = datasource;
  129. }
  130. public String getDiscardIdleConnectionsSeconds() {
  131. return discardIdleConnectionsSeconds;
  132. }
  133. public void setDiscardIdleConnectionsSeconds(String discardIdleConnectionsSeconds) {
  134. this.discardIdleConnectionsSeconds = discardIdleConnectionsSeconds;
  135. }
  136. }

这里配好过后要更改一下上面quartz.properties里面的这个,后面路径写你自己的

  1. #数据库连接池,将其设置为druid
  2. org.quartz.dataSource.qzDS.connectionProvider.class=com.ruoyi.system.config.DruidConnectionPr

注册调度工厂

  1. package com.ruoyi.system.config;
  2. import org.quartz.Scheduler;
  3. import org.quartz.SchedulerException;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.beans.factory.config.PropertiesFactoryBean;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.context.annotation.Configuration;
  8. import org.springframework.core.io.ClassPathResource;
  9. import org.springframework.scheduling.quartz.SchedulerFactoryBean;
  10. import java.io.IOException;
  11. @Configuration
  12. public class QuartzConfig {
  13. @Autowired
  14. private QuartzJobFactory jobFactory;
  15. @Bean
  16. public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
  17. //获取配置属性
  18. PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
  19. propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
  20. //在quartz.properties中的属性被读取并注入后再初始化对象
  21. propertiesFactoryBean.afterPropertiesSet();
  22. //创建SchedulerFactoryBean
  23. SchedulerFactoryBean factory = new SchedulerFactoryBean();
  24. factory.setQuartzProperties(propertiesFactoryBean.getObject());
  25. factory.setJobFactory(jobFactory);//支持在JOB实例中注入其他的业务对象
  26. factory.setApplicationContextSchedulerContextKey("applicationContextKey");
  27. factory.setWaitForJobsToCompleteOnShutdown(true);//这样当spring关闭时,会等待所有已经启动的quartz job结束后spring才能完全shutdown。
  28. factory.setOverwriteExistingJobs(false);//是否覆盖己存在的Job
  29. factory.setStartupDelay(10);//QuartzScheduler 延时启动,应用启动完后 QuartzScheduler 再启动
  30. return factory;
  31. }
  32. /**
  33. * 通过SchedulerFactoryBean获取Scheduler的实例
  34. * @return
  35. * @throws IOException
  36. * @throws SchedulerException
  37. */
  38. @Bean(name = "scheduler")
  39. public Scheduler scheduler() throws IOException, SchedulerException {
  40. Scheduler scheduler = schedulerFactoryBean().getScheduler();
  41. return scheduler;
  42. }
  43. }

注册任务工厂

  1. import org.quartz.spi.TriggerFiredBundle;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
  4. import org.springframework.scheduling.quartz.AdaptableJobFactory;
  5. import org.springframework.stereotype.Component;
  6. @Component
  7. public class QuartzJobFactory extends AdaptableJobFactory {
  8. @Autowired
  9. private AutowireCapableBeanFactory capableBeanFactory;
  10. @Override
  11. protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
  12. //调用父类的方法
  13. Object jobInstance = super.createJobInstance(bundle);
  14. //进行注入
  15. capableBeanFactory.autowireBean(jobInstance);
  16. return jobInstance;
  17. }
  18. }

新建一个任务job,你想定时执行的任务

  1. package com.ruoyi.system.task;
  2. import org.quartz.Job;
  3. import org.quartz.JobExecutionContext;
  4. import org.quartz.JobExecutionException;
  5. import org.slf4j.Logger;
  6. import org.slf4j.LoggerFactory;
  7. public class Msmjob implements Job {
  8. private static final Logger log = LoggerFactory.getLogger(Msmjob.class);
  9. @Override
  10. public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
  11. System.out.println("您的核酸任务于一个小时候开启,请及时完成核算任务");
  12. }
  13. }

添加service

  1. import java.util.Map;
  2. public interface QuartzService {
  3. /**
  4. * 添加任务可以传参数
  5. * @param clazzName
  6. * @param jobName
  7. * @param groupName
  8. * @param cronExp
  9. * @param param
  10. */
  11. void addJob(String clazzName, String jobName, String groupName, String cronExp, Map<String, Object> param);
  12. /**
  13. * 暂停任务
  14. * @param jobName
  15. * @param groupName
  16. */
  17. void pauseJob(String jobName, String groupName);
  18. /**
  19. * 恢复任务
  20. * @param jobName
  21. * @param groupName
  22. */
  23. void resumeJob(String jobName, String groupName);
  24. /**
  25. * 立即运行一次定时任务
  26. * @param jobName
  27. * @param groupName
  28. */
  29. void runOnce(String jobName, String groupName);
  30. /**
  31. * 更新任务
  32. * @param jobName
  33. * @param groupName
  34. * @param cronExp
  35. * @param param
  36. */
  37. void updateJob(String jobName, String groupName, String cronExp, Map<String, Object> param);
  38. /**
  39. * 删除任务
  40. * @param jobName
  41. * @param groupName
  42. */
  43. void deleteJob(String jobName, String groupName);
  44. /**
  45. * 启动所有任务
  46. */
  47. void startAllJobs();
  48. /**
  49. * 暂停所有任务
  50. */
  51. void pauseAllJobs();
  52. /**
  53. * 恢复所有任务
  54. */
  55. void resumeAllJobs();
  56. /**
  57. * 关闭所有任务
  58. */
  59. void shutdownAllJobs();
  60. }

添加实现类

  1. package com.ruoyi.system.service.impl;
  2. import com.alibaba.fastjson.JSONArray;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.ruoyi.system.service.QuartzService;
  5. import org.quartz.*;
  6. import org.quartz.impl.matchers.GroupMatcher;
  7. import org.slf4j.Logger;
  8. import org.slf4j.LoggerFactory;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.beans.factory.annotation.Qualifier;
  11. import org.springframework.jdbc.core.JdbcTemplate;
  12. import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
  13. import org.springframework.scheduling.quartz.JobDetailFactoryBean;
  14. import org.springframework.scheduling.quartz.SchedulerFactoryBean;
  15. import org.springframework.stereotype.Service;
  16. import javax.sql.DataSource;
  17. import java.text.SimpleDateFormat;
  18. import java.util.List;
  19. import java.util.Map;
  20. import java.util.Set;
  21. /**
  22. */
  23. @Service
  24. public class QuartzServiceImpl implements QuartzService {
  25. private static final Logger log = LoggerFactory.getLogger(QuartzServiceImpl.class);
  26. @Autowired
  27. private Scheduler scheduler;
  28. @Override
  29. public void addJob(String clazzName, String jobName, String groupName, String cronExp, Map<String, Object> param) {
  30. try {
  31. // 启动调度器,默认初始化的时候已经启动
  32. // scheduler.start();
  33. //构建job信息
  34. Class<? extends Job> jobClass = (Class<? extends Job>) Class.forName(clazzName);
  35. JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, groupName).build();
  36. //表达式调度构建器(即任务执行的时间)
  37. CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExp);
  38. //按新的cronExpression表达式构建一个新的trigger
  39. CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(jobName, groupName).withSchedule(scheduleBuilder).build();
  40. //获得JobDataMap,写入数据
  41. if (param != null) {
  42. trigger.getJobDataMap().putAll(param);
  43. }
  44. scheduler.scheduleJob(jobDetail, trigger);
  45. } catch (Exception e) {
  46. log.error("创建任务失败", e);
  47. }
  48. }
  49. @Override
  50. public void pauseJob(String jobName, String groupName) {
  51. try {
  52. scheduler.pauseJob(JobKey.jobKey(jobName, groupName));
  53. } catch (SchedulerException e) {
  54. log.error("暂停任务失败", e);
  55. }
  56. }
  57. @Override
  58. public void resumeJob(String jobName, String groupName) {
  59. try {
  60. scheduler.resumeJob(JobKey.jobKey(jobName, groupName));
  61. } catch (SchedulerException e) {
  62. log.error("恢复任务失败", e);
  63. }
  64. }
  65. @Override
  66. public void runOnce(String jobName, String groupName) {
  67. try {
  68. scheduler.triggerJob(JobKey.jobKey(jobName, groupName));
  69. } catch (SchedulerException e) {
  70. log.error("立即运行一次定时任务失败", e);
  71. }
  72. }
  73. @Override
  74. public void updateJob(String jobName, String groupName, String cronExp, Map<String, Object> param) {
  75. try {
  76. TriggerKey triggerKey = TriggerKey.triggerKey(jobName, groupName);
  77. CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
  78. if (cronExp != null) {
  79. // 表达式调度构建器
  80. CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExp);
  81. // 按新的cronExpression表达式重新构建trigger
  82. trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
  83. }
  84. //修改map
  85. if (param != null) {
  86. trigger.getJobDataMap().putAll(param);
  87. }
  88. // 按新的trigger重新设置job执行
  89. scheduler.rescheduleJob(triggerKey, trigger);
  90. } catch (Exception e) {
  91. log.error("更新任务失败", e);
  92. }
  93. }
  94. @Override
  95. public void deleteJob(String jobName, String groupName) {
  96. try {
  97. //暂停、移除、删除
  98. scheduler.pauseTrigger(TriggerKey.triggerKey(jobName, groupName));
  99. scheduler.unscheduleJob(TriggerKey.triggerKey(jobName, groupName));
  100. scheduler.deleteJob(JobKey.jobKey(jobName, groupName));
  101. } catch (Exception e) {
  102. log.error("删除任务失败", e);
  103. }
  104. }
  105. @Override
  106. public void startAllJobs() {
  107. try {
  108. scheduler.start();
  109. } catch (Exception e) {
  110. log.error("开启所有的任务失败", e);
  111. }
  112. }
  113. @Override
  114. public void pauseAllJobs() {
  115. try {
  116. scheduler.pauseAll();
  117. } catch (Exception e) {
  118. log.error("暂停所有任务失败", e);
  119. }
  120. }
  121. @Override
  122. public void resumeAllJobs() {
  123. try {
  124. scheduler.resumeAll();
  125. } catch (Exception e) {
  126. log.error("恢复所有任务失败", e);
  127. }
  128. }
  129. @Override
  130. public void shutdownAllJobs() {
  131. try {
  132. if (!scheduler.isShutdown()) {
  133. // 需谨慎操作关闭scheduler容器
  134. // scheduler生命周期结束,无法再 start() 启动scheduler
  135. scheduler.shutdown(true);
  136. }
  137. } catch (Exception e) {
  138. log.error("关闭所有的任务失败", e);
  139. }
  140. }
  141. }

这里再提供一个 Date类型转换Cron表达式的工具类,这样就能自定义时间了.

  1. package com.ruoyi.system.util;
  2. import java.text.SimpleDateFormat;
  3. import java.util.Date;
  4. public class TimeUtil {
  5. private static String formatDateByPattern(Date date, String dateFormat){
  6. SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
  7. String formatTimeStr = null;
  8. if (date != null) {
  9. formatTimeStr = sdf.format(date);
  10. }
  11. return formatTimeStr;
  12. }
  13. /**
  14. * Date转为cron表达式
  15. * @param date
  16. * @return
  17. */
  18. public static String getCron(java.util.Date date){
  19. String dateFormat="ss mm HH dd MM ? yyyy";
  20. return formatDateByPattern(date, dateFormat);
  21. }
  22. }

接下来只需要在你使用的地方注入service调用方法即可

  1. @Autowired
  2. private QuartzService quartzService;
  3. quartzService.addJob(Msmjob.class.getName(),Msmjob.class.getName(),
  4. "duanxin", TimeUtil.getCron(hsBuildingTask.getStartTime()),null);

数据库也有了

才疏学浅,有错误欢迎指出

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号