quartz框架使用@Autowired为null问题,quartz框架默认是不交给spring管理的,要想实现交给spring就需要自己配置JobFactory,QuartzConfig
1.依赖
<!--quartz--> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.3.2</version> </dependency>
2.JobFactory
import org.quartz.spi.TriggerFiredBundle; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.quartz.SpringBeanJobFactory; @Configuration public class MyJobFactory extends SpringBeanJobFactory { @Autowired private AutowireCapableBeanFactory capableBeanFactory; @Override protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception{ //调用父类的方法 Object jobInstance = super.createJobInstance(bundle); //进行注入 capableBeanFactory.autowireBean(jobInstance); return jobInstance; } }
3.QuartzConfig
import org.quartz.Scheduler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.quartz.SchedulerFactoryBean; @Configuration public class QuartzConfig { @Autowired private MyJobFactory myJobFactory; @Bean public SchedulerFactoryBean schedulerFactoryBean() { SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean(); schedulerFactoryBean.setJobFactory(myJobFactory); return schedulerFactoryBean; } @Bean public Scheduler scheduler() { return schedulerFactoryBean().getScheduler(); } }
4.Quartz任务管理类
import com.oigit.api.utils.DateUtil; import org.quartz.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import static org.quartz.TriggerBuilder.newTrigger; @Component public class QuartzManager { @Autowired private Scheduler scheduler; /** * @Description: 添加一个定时任务 * * @param jobName 任务名 * @param jobGroupName 任务组名 * @param triggerName 触发器名 * @param triggerGroupName 触发器组名 * @param jobClass 任务 * @param date 时间设置,参考quartz说明文档 */ @SuppressWarnings({ "unchecked", "rawtypes" }) public void addJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName, Class jobClass, String date,Long id) { try { // 任务名,任务组,任务执行类 JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroupName).build(); jobDetail.getJobDataMap().put("id",id); // 触发器 SimpleTrigger trigger = (SimpleTrigger) newTrigger() .withIdentity(triggerName, triggerGroupName) .startAt(new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(DateUtil.format(date, "yyyy-MM-dd HH:mm"))) // some Date .forJob(jobName, jobGroupName) // identify job with name, group strings .build(); // 调度容器设置JobDetail和Trigger scheduler.scheduleJob(jobDetail, trigger); // 启动 if (!scheduler.isShutdown()) { scheduler.start(); } } catch (Exception e) { throw new RuntimeException(e); } } /** * @Description: 修改一个任务的触发时间 * * @param jobName * @param jobGroupName * @param triggerName 触发器名 * @param triggerGroupName 触发器组名 * @param date 时间设置,参考quartz说明文档 */ public void modifyJobTime(String jobName, String jobGroupName, String triggerName, String triggerGroupName, String date) { try { TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName); SimpleTrigger trigger = (SimpleTrigger) scheduler.getTrigger(triggerKey); if (trigger == null) { return; } /** 方式一 :调用 rescheduleJob 开始 */ // 触发器 SimpleTrigger newTrigger = (SimpleTrigger) newTrigger() .withIdentity(triggerName, triggerGroupName) .startAt(new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(DateUtil.format(date, "yyyy-MM-dd HH:mm"))) // some Date .forJob(jobName, jobGroupName) // identify job with name, group strings .build(); scheduler.rescheduleJob(triggerKey, newTrigger); /** 方式二:先删除,然后在创建一个新的Job */ /*JobDetail jobDetail = sched.getJobDetail(JobKey.jobKey(jobName, jobGroupName)); Class<? extends Job> jobClass = jobDetail.getJobClass(); removeJob(jobName, jobGroupName, triggerName, triggerGroupName); addJob(jobName, jobGroupName, triggerName, triggerGroupName, jobClass, cron);*/ } catch (Exception e) { throw new RuntimeException(e); } } /** * @Description: 移除一个任务 * * @param jobName * @param jobGroupName * @param triggerName * @param triggerGroupName */ public void removeJob(String jobName, String jobGroupName,String triggerName, String triggerGroupName) { try { TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName); scheduler.pauseTrigger(triggerKey);// 停止触发器 scheduler.unscheduleJob(triggerKey);// 移除触发器 scheduler.deleteJob(JobKey.jobKey(jobName, jobGroupName));// 删除任务 } catch (Exception e) { throw new RuntimeException(e); } } /** * @Description:启动所有定时任务 */ public void startJobs() { try { scheduler.start(); } catch (Exception e) { throw new RuntimeException(e); } } /** * @Description:关闭所有定时任务 */ public void shutdownJobs() { try { if (!scheduler.isShutdown()) { scheduler.shutdown(); } } catch (Exception e) { throw new RuntimeException(e); } } }
5.业务逻辑执行的Job
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.oigit.api.common.Constant; import com.oigit.api.model.Wage; import com.oigit.api.model.WageDetail; import com.oigit.api.repository.UserRepository; import com.oigit.api.repository.WageDetailRepository; import com.oigit.api.repository.WageRepository; import com.oigit.api.service.TokenService; import com.oigit.api.utils.HttpUtil; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.StringUtils; import org.quartz.Job; import org.quartz.JobDataMap; import org.quartz.JobExecutionContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.net.URLEncoder; import java.util.List; import java.util.Optional; @Slf4j @Service public class SendWageJob implements Job { @Value("${trust.uri}") private String trustUri; @Autowired private UserRepository userRepository; @Override public void execute(JobExecutionContext jobExecutionContext) { JobDataMap dataMap = jobExecutionContext.getJobDetail().getJobDataMap(); long wageId = dataMap.getLongValue("id"); //业务逻辑 }
}
6.利用任务管理类添加任务
this.quartzManager.addJob("jobName-"+RandomStringUtils.randomAlphanumeric(32),"wageJobGroup","triggerName-"+RandomStringUtils.randomAlphanumeric(32),"wageTriggerGroup", SendWageJob.class,date,id);