[JAVA] Quartz timing tasks, automatic expiration, automatic shutdown, etc., integrate Springboot

Baal uncle 2022-11-24 21:24:46 阅读数:884

javaquartztimingtasksautomatic

1. pom.xml

<!--定时任务-->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>
<!-- 该依赖必加,里面有spring对schedule的支持 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>

2. 定时任务,Used to trigger timing task

/**
* Created with IntelliJ IDEA.
*
* @author: zhangenke
* @Date: 2018-12-20 on 10:21
* @description: 定时器,Used to trigger our mission:
*/
@Slf4j
@Component
public class MyScheduler {
@Autowired
private SchedulerFactoryBean schedulerFactoryBean;
private static Scheduler scheduler;
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Value("${submitOrderAuditExpiredValue}")
private int submitOrderAuditExpiredValue;
@Autowired
private GetCronUtils getCronUtils;
private final OrderDao orderDaoImpl;
private final SupplierDao supplierDaoImpl;
@Autowired
public MyScheduler(OrderDao orderDaoImpl, SupplierDao supplierDaoImpl) {
this.orderDaoImpl = orderDaoImpl;
this.supplierDaoImpl = supplierDaoImpl;
}
/**
* 项目启动时,Since the launch of need timing task method
*
* @throws SchedulerException
*/
public void scheduleJobs() throws SchedulerException {
log.info("开启定时任务:~~~~~~~~~~");
scheduler = schedulerFactoryBean.getScheduler();
this.orderAuditExpired();
this.bidExpired();
}
/**
* Orders order review automatically expired tasks,Since the launch will be executed after
*
* @param jobName 任务名
* @param jobGroupName 任务组名
* @param triggerName 触发器名
* @param triggerGroupName 触发器组名
* @throws SchedulerException
*/
private void orderAuditExpired() throws SchedulerException {
System.out.println("Began to query the order review order,Set a time for point-to-point after,Every minute a update task******************");
System.out.println("现在时间:" + simpleDateFormat.format(new Date()));
try {
Map<JobDetail, Set<? extends Trigger>> map = Maps.newHashMap();
log.info("Being queried all orders pending order list~~~~~~~~~");
List<Order> orders = orderDaoImpl.listOrderAuditExpired();
if (orders.size() > Num.ZERO.getNum()) {
for (int i = 0; i < orders.size(); i++) {
log.info("下单时间:{}", simpleDateFormat.format(orders.get(i).getCreateAt()));
String cron = getCronUtils.getCron(orders.get(i).getCreateAt(), submitOrderAuditExpiredValue);
if (getCronUtils.compareTime(orders.get(i).getCreateAt(), submitOrderAuditExpiredValue)) {
cron = getCronUtils.getNowRandomCron();
}
log.info("时间表达式为:{}", cron);
// 1. 创建一个JodDetail实例 将该实例与Hello job class绑定 (链式写法)
// 定义Job类为ScheduledJob类,这是真正的执行逻辑所在
JobDetail jobDetail = JobBuilder.newJob(OrderAuditExpiredJob.class)
.withIdentity(orders.get(i).getOrderId(), orders.get(i).getOrderId())
.build();
CronTrigger cronTrigger = TriggerBuilder.newTrigger()
.withIdentity(orders.get(i).getOrderId(), orders.get(i).getOrderId())
.withSchedule(
CronScheduleBuilder.cronSchedule(cron)
).build();
// 绑定 jobDetail 和 trigger,Register it into Scheduler 当中 ,The return value is the beginning of the last task execution time
//scheduler.scheduleJob(jobDetail, cronTrigger);
Set<Trigger> set = Sets.newHashSet();
set.add(cronTrigger);
map.put(jobDetail, set);
log.info("新增了:{}条", i + 1);
}
log.info("map size:{}", map.size());
//The new timing task group
scheduler.scheduleJobs(map, false);
} else {
log.info("No order audit tasks need to audit:******");
}
} catch (Exception e) {
log.error("Order review timing task mistake:{}", e);
}
}
private void bidExpired() throws SchedulerException {
System.out.println("Began to query does not have the bid opening and closing open tender set a time for point-to-point after,每分钟一次******************");
System.out.println("现在时间:" + simpleDateFormat.format(new Date()));
try {
Map<JobDetail, Set<? extends Trigger>> map = Maps.newHashMap();
log.info("Being queried all has the bid opening and not as tender and bid list~~~~~~~~~");
List<Map> maps = supplierDaoImpl.listBidByExpired();
//bidId,openBidTime
if (maps.size() > Num.ZERO.getNum()) {
for (int i = 0; i < maps.size(); i++) {
log.info("开标时间:{}", simpleDateFormat.format(maps.get(i).get("openBidTime")));
String cron = getCronUtils.getCron(simpleDateFormat.parse(maps.get(i).get("openBidTime").toString()), 0);
if (getCronUtils.compareTime(simpleDateFormat.parse(maps.get(i).get("openBidTime").toString()), 0)) {
cron = getCronUtils.getNowRandomCron();
}
log.info("时间表达式为:{}", cron);
JobDetail jobDetail = JobBuilder.newJob(BidExpiredJob.class)
.withIdentity(maps.get(i).get("bidId").toString(), maps.get(i).get("bidId").toString())
.build();
CronTrigger cronTrigger = TriggerBuilder.newTrigger()
.withIdentity(maps.get(i).get("bidId").toString(), maps.get(i).get("bidId").toString())
.withSchedule(
CronScheduleBuilder.cronSchedule(cron)
).build();
Set<Trigger> set = Sets.newHashSet();
set.add(cronTrigger);
map.put(jobDetail, set);
log.info("新增了:{}条", i + 1);
}
log.info("map size:{}", map.size());
//The new timing task group
scheduler.scheduleJobs(map, false);
} else {
log.info("Temporarily on the bid opening and cut-off and closed tender:******");
}
} catch (Exception e) {
log.error("Close the tender timing task mistake:{}", e);
}
}
/**
* 新增定时任务
*
* @param cron 时间表达式
* @param jobName 任务名
* @param jobGroupName 任务组名
* @param triggerName 触发器名
* @param triggerGroupName 触发器组名
* @param expiredClass To the time required to perform the business logic of the class
* @throws SchedulerException
*/
public void addJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName, Date date, int expiredValue, Class<? extends Job> expiredClass) throws SchedulerException {
// 通过JobBuilder构建JobDetail实例,JobDetail规定只能是实现Job接口的实例
// JobDetail 是具体Job实例
JobDetail jobDetail = JobBuilder.newJob(expiredClass).withIdentity(jobName, jobGroupName).build();
String cron = getCronUtils.getCron(date, expiredValue);
// 基于表达式构建触发器
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
// CronTrigger表达式触发器 继承于Trigger
// TriggerBuilder 用于构建触发器实例
CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(triggerName, triggerGroupName)
.withSchedule(scheduleBuilder).build();
Date date1 = scheduler.scheduleJob(jobDetail, cronTrigger);
log.info("New timing task success,任务名:{},下次执行时间:{}", jobName, simpleDateFormat.format(date1));
}
/**
* 修改某个任务的执行时间
*
* @param triggerName 触发器名
* @param triggerGroupName 触发器组名
* @param cron 时间表达式
* @throws SchedulerException
*/
public void modifyJob(String triggerName, String triggerGroupName, String cron) throws SchedulerException {
TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
CronTrigger newTrigger = TriggerBuilder.newTrigger().withIdentity(triggerName, triggerGroupName)
.withSchedule(scheduleBuilder).build();
scheduler.rescheduleJob(triggerKey, newTrigger);
}
/**
* 获取某个任务的状态
*
* @param triggerName
* @param triggerGroupName
* @return
* @throws SchedulerException
*/
public String getJobStatus(String triggerName, String triggerGroupName) throws SchedulerException {
TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
return scheduler.getTriggerState(triggerKey).name();
}
/**
* 暂停某个任务
*
* @param jobName
* @param jobGroupName
* @throws SchedulerException
*/
public void pauseJob(String jobName, String jobGroupName) throws SchedulerException {
scheduler.pauseJob(JobKey.jobKey(jobName, jobGroupName));
}
/**
* 恢复某个任务
*
* @param jobName
* @param jobGroupName
* @throws SchedulerException
*/
public void resumeJob(String jobName, String jobGroupName) throws SchedulerException {
scheduler.resumeJob(JobKey.jobKey(jobName, jobGroupName));
}
/**
* 删除某个任务 (An order is being reviewed,Need to delete this task)
*
* @param jobName 任务名
* @param jobGroupName 任务组名
* @throws SchedulerException
*/
public void deleteJob(String jobName, String jobGroupName) throws SchedulerException {
scheduler.deleteJob(JobKey.jobKey(jobName, jobGroupName));
}
}

3. The listener will call to ensure project start-up time

/**
* Created with IntelliJ IDEA.
*
* @author: zhangenke
* @Date: 2018-12-19 on 17:29
* @description: The listener will call to ensure project start-up time,我们的定时任务,代码如下:
*/
@Slf4j
@Configuration
public class SchedulerListener implements ApplicationListener<ContextRefreshedEvent> {
@Autowired
private MyScheduler myScheduler;
@Autowired
private JobFactory jobFactory;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
try {
myScheduler.scheduleJobs();
} catch (SchedulerException e) {
e.printStackTrace();
}
}
/**
* 配置SchedulerFactoryBean
* A method forBean并交给Spring容器管理
*/
@Bean
public SchedulerFactoryBean schedulerFactoryBean() {
// Spring提供SchedulerFactoryBean为Scheduler提供配置信息,并被Spring容器管理其生命周期
SchedulerFactoryBean factory = new SchedulerFactoryBean();
// 设置自定义Job Factory,用于Spring管理Job bean
factory.setJobFactory(jobFactory);
return factory;
}
}

4. 解决Springboot在Quartz中注入Bean的问题

package com.construn.procure.quartz;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.stereotype.Component;
/**
* Created with IntelliJ IDEA.
*
* @author: zhangenke @Date: 2018-12-26 on 15:56
* @description: 解决SpringBoot不能再Quartz中注入Bean的问题
*/
@Component
public class JobFactory extends org.springframework.scheduling.quartz.SpringBeanJobFactory {
/** AutowireCapableBeanFactory接口是BeanFactory的子类 可以连接和填充那些生命周期不被Spring管理的已存在的bean实例 */
@Autowired
private AutowireCapableBeanFactory beanFactory;
/** 创建Job实例 */
@Override
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
// 实例化对象
Object job = super.createJobInstance(bundle);
// 进行注入(Spring管理该Bean)
beanFactory.autowireBean(job);
// 返回对象
return job;
}
}

5. One of the automatic expiration class

/**
* Created with IntelliJ IDEA.
*
* @author: zhangenke @Date: 2018-12-20 on 10:21
* @description: Orders order review automatically expired tasks
* @description: 01-21 遇到Job初始化错误,原因是,JobClass must have a default no arguments constructor!!!
*/
@Slf4j
@Component
public class BidExpiredJob implements Job {
private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Autowired private SupplierDao supplierDaoImpl;
@Autowired private UserClient userClient;
public BidExpiredJob() {}
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
log.info("Orders for expired tasks implemented:{}", simpleDateFormat.format(new Date()));
try {
log.info("The tender is closing ~~~~~~");
userClient.updateBidStatusByExpired(jobExecutionContext.getJobDetail().getKey().getName());
int count =
supplierDaoImpl.updateBidStatusByExpired(
jobExecutionContext.getJobDetail().getKey().getName());
if (count != 1) {
log.info("The tender status is not bid opening status,Has been GuanBiao,So don't automatically update");
} else {
log.info("Has been automatically expire:{}条", count);
}
log.info(
"删除任务:{},必须是true,Otherwise encountered serious mistake",
jobExecutionContext
.getScheduler()
.deleteJob(jobExecutionContext.getJobDetail().getKey()));
} catch (Exception e) {
log.error("Orders for expired tasks go wrong,{}", e);
}
}
}

6. Time expression tools

/**
* Created with IntelliJ IDEA.
*
* @author: zhangenke
* @Date: 2018-12-26 on 11:52
* @description: 获取定时任务,时间表达式
*/
@Component
@Slf4j
public class GetCronUtils {
private static final String SPACE = " ";
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* Access time expression,
*
* @param date 创建时间
* @param expiredValue 过期值(单位秒)
* @return
*/
public String getCron(Date date, int expiredValue) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.SECOND, expiredValue);
return cron(calendar);
}
public String getNowRandomCron() {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MINUTE, new Random().nextInt(9) + 1);
return cron(calendar);
}
/**
* If his time plus five days,比现在的时间大,说明,已经过期,Need immediately perform expiration logic
*
* @param oldDate
* @param expiredValue 过期值
* @return
*/
public boolean compareTime(Date oldDate, int expiredValue) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(oldDate);
calendar.add(Calendar.SECOND, expiredValue);
log.info("任务时间 + {}天:{},现在时间:{}", expiredValue, simpleDateFormat.format(calendar.getTime()),
simpleDateFormat.format(new Date()));
if (calendar.getTime().getTime() < System.currentTimeMillis()) {
log.info("任务时间 + {}Day was a little with the current time,So have serious time out,Random expired tasks now", expiredValue);
return true;
}
return false;
}
private String cron(Calendar calendar) {
int year = calendar.get(Calendar.YEAR);
String month = (calendar.get(Calendar.MONTH) + 1) + "";
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
log.info("年,月,日,时,分,秒:{}-{}-{} {}:{}:{}", year, month, day, hour, minute, second);
return second + SPACE + minute + "/1" + SPACE + hour +
SPACE + day + SPACE + month + SPACE + "?" + SPACE + "*";
}
}

7. 总结:

1. 首先要明确需求,And then make a decision technology selection;

2. Meet new technology,Open a few more blog garden、CSDN博客等Demo,然后自己调试;

3. 遇到问题,再进行google解决.There are many predecessors have solve,You just need to find;

4. Rookie to share,大佬勿喷;

5. @Autowired此注解,Can't literally into the constructor class,否则会出现问题;

6. All the problems,I have been solved and added comments,都能看懂;

copyright:author[Baal uncle],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/328/202211242120377406.html