quartzJob简单使用(自用,很简洁)
配置文件
spring: datasource: driverClassName: com.mysql.cj.jdbc.Driver url: jdbc:mysql://${MYSQL_HOST:10.10.102.90}:${MYSQL_PORT:3306}/online_test_system?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai username: ${WPG_MYSQL_USER:root} password: ${WPG_MYSQL_PSWD:wpg@2020} type: com.alibaba.druid.pool.DruidDataSource # 数据源其他配置 initialSize: 5 minIdle: 5 maxActive: 20 maxWait: 60000 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: SELECT 1 FROM DUAL testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙 filters: stat,wall maxPoolPreparedStatementPerConnectionSize: 20 useGlobalDataSourceStat: true connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500 quartz: driverClassName: com.mysql.cj.jdbc.Driver url: jdbc:mysql://${MYSQL_MASTER_URL:10.10.102.90}:${MYSQL_MASTER_PORT:3306}/quartz?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai username: root password: wpg@2020 quartz: job-store-type: jdbc scheduler-name: modelScheduler wait-for-jobs-to-complete-on-shutdown: true jdbc: initialize-schema: never properties: org: quartz: scheduler: instanceName: clusteredScheduler instanceId: AUTO jobStore: class: org.quartz.impl.jdbcjobstore.JobStoreTX driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelegate tablePrefix: qrtz_ isClustered: true clusterCheckinInterval: 10000 useProperties: false threadPool: class: org.quartz.simpl.SimpleThreadPool threadCount: 10 threadPriority: 5 threadsInheritContextClassLoaderOfInitializingThread: true
quartz持久化数据库配置
/** * @author mxb * @date 2022/08/15 9:57 * 加载quartz所需数据 配置多数据源 * */ @Configuration public class QuartzDataSourceConfiguration { private static HikariDataSource createHikariDataSource(DataSourceProperties properties) { // 创建 HikariDataSource 对象 HikariDataSource dataSource = properties.initializeDataSourceBuilder().type(HikariDataSource.class).build(); // 设置线程池名 if (StringUtils.hasText(properties.getName())) { dataSource.setPoolName(properties.getName()); } return dataSource; } /** * 创建 quartz 数据源的配置对象 * 读取 spring.datasource.quartz 配置到 DataSourceProperties 对象 */ @Primary @Bean(name = "quartzDataSourceProperties") @ConfigurationProperties(prefix = "spring.datasource.quartz") public DataSourceProperties quartzDataSourceProperties() { return new DataSourceProperties(); } /** * 创建 quartz 数据源 */ @Bean(name = "quartzDataSource") @ConfigurationProperties(prefix = "spring.datasource.quartz.hikari") @QuartzDataSource public DataSource quartzDataSource() { // 获得 DataSourceProperties 对象 DataSourceProperties properties = this.quartzDataSourceProperties(); // 创建 HikariDataSource 对象 return createHikariDataSource(properties); } }
创建定时任务
import com.knowledge.base.web.job.HandInExaminationPaperTiming; import lombok.SneakyThrows; import org.quartz.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Date; import java.util.HashMap; /** * @author: mxb * @date: 2022/8/15 9:12 */ @Service public class EndExamJobService { @Autowired private Scheduler scheduler; @SneakyThrows public void addJob(String answerId, Date startTime) { HashMap<String, Object> paramMap = new HashMap<>(); paramMap.put("answerId", answerId); // 创建任务触发器 Trigger trigger = TriggerBuilder.newTrigger() .withIdentity(answerId, HandInExaminationPaperTiming.class.getName()) .startAt(startTime) .build(); this.createJob(answerId, paramMap, trigger); } @SneakyThrows public void addJob(String answerId, Date startTime, Date endTime) { HashMap<String, Object> paramMap = new HashMap<>(); paramMap.put("answerId", answerId); // 创建任务触发器,时间间隔内,每五分钟执行一次 Trigger trigger = TriggerBuilder.newTrigger() .withIdentity(answerId, HandInExaminationPaperTiming.class.getName()) .withSchedule(SimpleScheduleBuilder.repeatMinutelyForever(5)) .startAt(startTime) .endAt(endTime) .build(); this.createJob(answerId, paramMap, trigger); } @SneakyThrows public void addJob(String answerId, String coreExpression) { HashMap<String, Object> paramMap = new HashMap<>(); paramMap.put("answerId", answerId); // 使用job类名作为组名 String groupName = this.getClass().getSimpleName(); // 基于core表达式构建触发器 CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(coreExpression); CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(answerId, groupName).withSchedule(cronScheduleBuilder).build(); this.createJob(answerId, paramMap, trigger); } /** * 创建定时任务 * * @param jobName * @param paramMap * @param trigger * @throws SchedulerException */ private void createJob(String jobName, HashMap<String, Object> paramMap, Trigger trigger) throws SchedulerException { // 创建任务 JobDetail jobDetail = JobBuilder.newJob(HandInExaminationPaperTiming.class).withIdentity(jobName, HandInExaminationPaperTiming.class.getSimpleName()).build(); // 添加参数 jobDetail.getJobDataMap().putAll(paramMap); // 将触发器与任务绑定到调度器内 scheduler.scheduleJob(jobDetail, trigger); } }
任务执行类
/** * @author mxb * @date 2022/08/15 11:16 * 读取数据定时器执行类 */ public class HandInExaminationPaperTiming implements Job { private static final Logger log = LoggerFactory.getLogger(HandInExaminationPaperTiming.class); @Override @SneakyThrows public void execute(JobExecutionContext jobExecutionContext) { try { //从JobDataMap中获取通信信息(answerId) JobDataMap requestDataMap = jobExecutionContext.getMergedJobDataMap(); String answerId = (String) requestDataMap.get("answerId"); //交卷业务逻辑 System.out.println(answerId+" "+LocalDateTime.now()+"-------------------"+Thread.currentThread().getName()); } catch (Exception e) { log.error("DataForecastJobBase -> execute() 定时任务出现错误"); } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix