Spring使用Quartz定时调度Job无法Autowired注入Service的解决方案

Spring使用Quartz定时调度Job无法Autowired注入Service的解决方案

1. 当时我有个项目要使用调度,所以选择Spring-Quartz,但是遇到了问题就是无法Autowired注入Service。

2. 利用Quartz可以实现定时任务,但在跟Spring整合后,直接在Job中注解方式注入Service后运行却报空指针异常。

原因是Quartz初始化是自己的JobContext,不同于Spring的ApplicationContext,所以无法直接注入

3.具体做法是直接getBean()的方式来获取service的

1
2
3
4
5
6
7
8
9
10
11
public class DispatchWork implements Job {
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
String jobName = jobExecutionContext.getJobDetail().getKey().getName();
String group = jobExecutionContext.getTrigger().getKey().getGroup();
RunKettleSerive runKettleSerive= SpringContextHolder.getBean(RunKettleSerive.class);
runKettleSerive.runKettleScript(jobName,group);
/* runKettleSerive.runKettleScript(jobName,group);*/
}
}

4.关键代码就是RunKettleSerive runKettleSerive= SpringContextHolder.getBean(RunKettleSerive.class)。

后面附上我的spring.xml,Spring-Quartz.xml,和主要的java代码
spring.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd"
default-lazy-init="true">
<description>Spring Configuration</description>
<!-- 加载配置属性文件 -->
<context:property-placeholder ignore-unresolvable="true" location="classpath:config.properties" />
<!-- 加载应用属性实例,在JAVA类中可以 @Value("#{APP_PROP['jdbc.driver']}") 来获取属性文件中jdbc.driver的值 -->
<util:properties id="APP_PROP" location="classpath:config.properties" local-override="true" />
<!-- Controller注解由springMVC扫描 -->
<context:component-scan base-package="com.pactera"><!-- base-package 如果多个,用“,”分隔 -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!--注入spring-quartz-->
<import resource="spring-quartz.xml"/>
</beans>
spring-quartz.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
">
<!-- 配置调度器工厂(SchedulerFactoryBean) -->
<bean name="startQuertz"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="myJobTrigger" />
</list>
</property>
</bean>
<!-- 配置Cron触发器(CronTriggerFactoryBean) -->
<bean id="myJobTrigger"
class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail">
<ref bean="myJobDetail" />
</property>
<property name="cronExpression">
<!-- 每隔10分钟执行 -->
<value>0 0/2 * * * ?</value>
<!-- <value>0/20 * * * * ?</value> -->
<!-- 每隔2小时 <value>* * */2 * * ?</value> -->
</property>
</bean>
<!-- 配置方法调用任务工厂(XXXJobDetailFactoryBean) -->
<bean id="myJobDetail"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject">
<ref bean="myJob" />
</property>
<property name="targetMethod">
<value>doWork</value>
</property>
</bean>
<!-- 工作的bean -->
<bean id="myJob" class="com.pactera.modules.sys.job.DispatchJob" lazy-init="true">
</bean>
<!--&lt;!&ndash; 工作的bean &ndash;&gt;
<bean id="myJob2" class="com.pactera.modules.sys.job.DispatchWork" lazy-init="true">
<property name="runKettleSerive" >
<ref bean="unKettleSeriveImpl" />
</property>
</bean>-->
</beans>
DispatchJob.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import com.pactera.common.support.CustomerContextHolder;
import com.pactera.common.util.SchedulerUtil;
import com.pactera.modules.datadistribute.services.DistributeShellService;
import com.pactera.modules.distribute.service.DistributeWorkInfoService;
import com.pactera.modules.runscipt.service.RunKettleSerive;
import com.pactera.modules.runscipt.service.RunScriptService;
import com.pactera.modules.settings.service.DamDependencyService;
import com.pactera.modules.settings.service.DamFrequencyService;
import com.pactera.modules.settings.service.DamVariableDatadateService;
import org.apache.log4j.Logger;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* Created by echo_ on 2017/12/8.
* @author sxl
*/
public class DispatchJob {
private static final Logger logger = Logger.getLogger(DispatchJob.class);
@Autowired
private DamVariableDatadateService damVariableDatadateService;
@Autowired
private DistributeShellService distributeShellService;
@Autowired
private DistributeWorkInfoService distributeWorkInfoService;
@Autowired
private RunScriptService runScriptService;
@Autowired
private RunKettleSerive runKettleScript;
@Autowired
private DamDependencyService damDependencyService;
@Autowired
private DamFrequencyService damFrequencyService;
public void doWork() throws SchedulerException {
doShellWork();
System.out.println(new Date());
}
public void doShellWork() throws SchedulerException {
CustomerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE_DAM);
List<Map<String, Object>> maps = distributeShellService.selectDistributeTask();
SchedulerFactory schedulerfactory = new StdSchedulerFactory();
Scheduler scheduler = schedulerfactory.getScheduler();
for (int i=0;i<maps.size();i++){
List<String> wid_List = Arrays.asList(StringUtils.commaDelimitedListToStringArray(maps.get(i).get("WORK_ID").toString()));
//作业idlist
for (int k=0;k<wid_List.size();k++){
SchedulerUtil.createScheduleJob(scheduler, maps.get(i).get("TASK_ID").toString(), wid_List.get(k), damFrequencyService.selectTriggerRuleById(maps.get(i).get("TASK_ID").toString())
, DispatchWork.class);
}
}
CustomerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE);
}
}
DispatchWork.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.pactera.modules.sys.job;
import com.pactera.common.util.SpringContextHolder;
import com.pactera.modules.runscipt.service.RunKettleSerive;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
/**
* @author song
* @date created in 2018-02-01 19:17
*/
public class DispatchWork implements Job {
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
String jobName = jobExecutionContext.getJobDetail().getKey().getName();
String group = jobExecutionContext.getTrigger().getKey().getGroup();
//这样就拿到service了
RunKettleSerive runKettleSerive= SpringContextHolder.getBean(RunKettleSerive.class);
runKettleSerive.runKettleScript(jobName,group);
/* runKettleSerive.runKettleScript(jobName,group);*/
}
}
接口SchedulerUtil,处理调度
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package com.pactera.common.util;
import com.pactera.modules.sys.job.DispatchWork;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
/**
* @author song
* @date created in 2018-01-19 15:35
*/
public class SchedulerUtil {
/**
* 创建定时任务
*
* @param scheduler the scheduler
* @param jobName the job name
* @param jobGroup the job group
* @param cronExpression the cron expression
* @param clazz job class
*/
public static void createScheduleJob(Scheduler scheduler, String jobName, String jobGroup,
String cronExpression, Class<? extends Job> clazz) throws SchedulerException {
//通过schedulerFactory获取一个调度器
SchedulerFactory schedulerfactory=new StdSchedulerFactory();
try{
// 通过schedulerFactory获取一个调度器
scheduler=schedulerfactory.getScheduler();
// 创建jobDetail实例,绑定Job实现类
// 指明job的名称,所在组的名称,以及绑定job类
JobDetail job= JobBuilder.newJob(DispatchWork.class).withIdentity(jobName, jobGroup).build();
Trigger trigger=TriggerBuilder.newTrigger().withIdentity(jobName, jobGroup)
.withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
.startNow().build();
// 把作业和触发器注册到任务调度中
scheduler.scheduleJob(job, trigger);
// 启动调度
scheduler.start();
}catch(Exception e){
e.printStackTrace();
}
}
/**
* 创建定时任务
*
* @param scheduler the scheduler
* @param jobName the job name
* @param jobGroup the job group
* @param cronExpression the cron expression
*/
public static void updateScheduleJob(Scheduler scheduler, String jobName, String jobGroup,
String cronExpression) throws SchedulerException {
TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroup);
//获取trigger,即在spring配置文件中定义的 bean id="myTrigger"
CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
//表达式调度构建器
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
//按新的cronExpression表达式重新构建trigger
try {
trigger = trigger.getTriggerBuilder().withIdentity(triggerKey)
.withSchedule(scheduleBuilder).build();
}catch (Exception e){
System.out.println("errMsg"+e);
return;
}
//按新的trigger重新设置job执行
scheduler.rescheduleJob(triggerKey, trigger);
}
/**
* 暂停任务
*
* @param scheduler the scheduler
* @param jobName the job name
* @param jobGroup the job group
*/
public static void pauseJob(Scheduler scheduler, String jobName, String jobGroup) throws SchedulerException {
JobKey jobKey = JobKey.jobKey(jobName, jobGroup);
scheduler.pauseJob(jobKey);
}
/**
* 恢复任务
*
* @param scheduler the scheduler
* @param jobName the job name
* @param jobGroup the job group
*/
public static void resumeJob(Scheduler scheduler, String jobName, String jobGroup) throws SchedulerException {
JobKey jobKey = JobKey.jobKey(jobName, jobGroup);
scheduler.resumeJob(jobKey);
}
/**
* 删除任务
*
* @param scheduler the scheduler
* @param jobName the job name
* @param jobGroup the job group
*/
public static void deleteJob(Scheduler scheduler, String jobName, String jobGroup) throws SchedulerException {
JobKey jobKey = JobKey.jobKey(jobName, jobGroup);
scheduler.deleteJob(jobKey);
}
/**
* 立即运行
*
* @param scheduler the scheduler
* @param jobName the job name
* @param jobGroup the job group
*/
public static void triggerJob(Scheduler scheduler, String jobName, String jobGroup) throws SchedulerException {
JobKey jobKey = JobKey.jobKey(jobName, jobGroup);
scheduler.triggerJob(jobKey);
}
}
这几天需要用到定时任务调度,因此转向quartz的学习,特此记录下来。

quartz使用起来及其方便,与spring整合配置,只需要写一个类继承QuartzJobBean,重写其executeInternal(JobExecutionContext arg0)即可,我们只需要将自己的逻辑代码写在该方法即可。一旦你配置好实现类并设定好调度时间,Quartz将密切注意剩余时间。当调度程序确定该是执行作业的时候,Quartz框架将调用你作业类上的executeInternal()方法并执行相应的任务。无需报告任何东西给调度器或调用任何特定的东西。仅仅执行任务和结束任务即可。如果配置你的作业在随后再次被调用,Quartz框架将在恰当的时间再次调用它。

quartz有三个核心概念,调度器、任务和触发器。三者关系简单来说就是,调度器负责调度各个任务,到了某个时刻或者过了一定时间,触发器触动了,特定任务便启动执行。概念相对应的类和接口有:

  1)JobDetail:描述任务的相关情况,包括配置任务执行的类和方法。

  2)Trigger:描述出发Job执行的时间触发规则。有SimpleTrigger和CronTrigger两个子类代表两种方式,一种是每隔多少分钟小时执行,则用SimpleTrigger;另一种是日历相关的重复时间间隔,如每天凌晨,每周星期一运行的话,通过Cron表达式便可定义出复杂的调度方案。

  3)Scheduler:代表一个Quartz的独立运行容器,Trigger和JobDetail要注册到Scheduler中才会生效,也就是让调度器知道有哪些触发器和任务,才能进行按规则进行调度任务。
quartz的配置一般有两种,一种是配置无参数的任务,就是一个普通方法,要求该执行任务的方法必须为无参方法,否则会报错。另一种是配置可传参方法,因为这里我需要给任务传递一些参数,所以采用第二种配置方法。

首先,需要下载quartz和spring对其提供支持的jar包。我这里采用的是quartz-2.2.1.jar,spring-context-support-4.2.4.RELEASE.jar,下载其他版本请注意包版本之间的兼容。

title: Spring使用Quartz定时调度Job无法Autowired注入Service的解决方案
tags:

  • Quartz
  • 文章
    categories:
  • Spring
    date: 2018-01-22 13:27:22
    permalink: Spring_Quartz_Job_Autowired

Spring使用Quartz定时调度Job无法Autowired注入Service的解决方案

1. 当时我有个项目要使用调度,所以选择Spring-Quartz,但是遇到了问题就是无法Autowired注入Service。

2. 利用Quartz可以实现定时任务,但在跟Spring整合后,直接在Job中注解方式注入Service后运行却报空指针异常。

原因是Quartz初始化是自己的JobContext,不同于Spring的ApplicationContext,所以无法直接注入

3.具体做法是直接getBean()的方式来获取service的

1
2
3
4
5
6
7
8
9
10
11
public class DispatchWork implements Job {
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
String jobName = jobExecutionContext.getJobDetail().getKey().getName();
String group = jobExecutionContext.getTrigger().getKey().getGroup();
RunKettleSerive runKettleSerive= SpringContextHolder.getBean(RunKettleSerive.class);
runKettleSerive.runKettleScript(jobName,group);
/* runKettleSerive.runKettleScript(jobName,group);*/
}
}

4.关键代码就是RunKettleSerive runKettleSerive= SpringContextHolder.getBean(RunKettleSerive.class)。

后面附上我的spring.xml,Spring-Quartz.xml,和主要的java代码
spring.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd"
default-lazy-init="true">
<description>Spring Configuration</description>
<!-- 加载配置属性文件 -->
<context:property-placeholder ignore-unresolvable="true" location="classpath:config.properties" />
<!-- 加载应用属性实例,在JAVA类中可以 @Value("#{APP_PROP['jdbc.driver']}") 来获取属性文件中jdbc.driver的值 -->
<util:properties id="APP_PROP" location="classpath:config.properties" local-override="true" />
<!-- Controller注解由springMVC扫描 -->
<context:component-scan base-package="com.pactera"><!-- base-package 如果多个,用“,”分隔 -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!--注入spring-quartz-->
<import resource="spring-quartz.xml"/>
</beans>
spring-quartz.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
">
<!-- 配置调度器工厂(SchedulerFactoryBean) -->
<bean name="startQuertz"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="myJobTrigger" />
</list>
</property>
</bean>
<!-- 配置Cron触发器(CronTriggerFactoryBean) -->
<bean id="myJobTrigger"
class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail">
<ref bean="myJobDetail" />
</property>
<property name="cronExpression">
<!-- 每隔10分钟执行 -->
<value>0 0/2 * * * ?</value>
<!-- <value>0/20 * * * * ?</value> -->
<!-- 每隔2小时 <value>* * */2 * * ?</value> -->
</property>
</bean>
<!-- 配置方法调用任务工厂(XXXJobDetailFactoryBean) -->
<bean id="myJobDetail"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject">
<ref bean="myJob" />
</property>
<property name="targetMethod">
<value>doWork</value>
</property>
</bean>
<!-- 工作的bean -->
<bean id="myJob" class="com.pactera.modules.sys.job.DispatchJob" lazy-init="true">
</bean>
<!--&lt;!&ndash; 工作的bean &ndash;&gt;
<bean id="myJob2" class="com.pactera.modules.sys.job.DispatchWork" lazy-init="true">
<property name="runKettleSerive" >
<ref bean="unKettleSeriveImpl" />
</property>
</bean>-->
</beans>
DispatchJob.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import com.pactera.common.support.CustomerContextHolder;
import com.pactera.common.util.SchedulerUtil;
import com.pactera.modules.datadistribute.services.DistributeShellService;
import com.pactera.modules.distribute.service.DistributeWorkInfoService;
import com.pactera.modules.runscipt.service.RunKettleSerive;
import com.pactera.modules.runscipt.service.RunScriptService;
import com.pactera.modules.settings.service.DamDependencyService;
import com.pactera.modules.settings.service.DamFrequencyService;
import com.pactera.modules.settings.service.DamVariableDatadateService;
import org.apache.log4j.Logger;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* Created by echo_ on 2017/12/8.
* @author sxl
*/
public class DispatchJob {
private static final Logger logger = Logger.getLogger(DispatchJob.class);
@Autowired
private DamVariableDatadateService damVariableDatadateService;
@Autowired
private DistributeShellService distributeShellService;
@Autowired
private DistributeWorkInfoService distributeWorkInfoService;
@Autowired
private RunScriptService runScriptService;
@Autowired
private RunKettleSerive runKettleScript;
@Autowired
private DamDependencyService damDependencyService;
@Autowired
private DamFrequencyService damFrequencyService;
public void doWork() throws SchedulerException {
doShellWork();
System.out.println(new Date());
}
public void doShellWork() throws SchedulerException {
CustomerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE_DAM);
List<Map<String, Object>> maps = distributeShellService.selectDistributeTask();
SchedulerFactory schedulerfactory = new StdSchedulerFactory();
Scheduler scheduler = schedulerfactory.getScheduler();
for (int i=0;i<maps.size();i++){
List<String> wid_List = Arrays.asList(StringUtils.commaDelimitedListToStringArray(maps.get(i).get("WORK_ID").toString()));
//作业idlist
for (int k=0;k<wid_List.size();k++){
SchedulerUtil.createScheduleJob(scheduler, maps.get(i).get("TASK_ID").toString(), wid_List.get(k), damFrequencyService.selectTriggerRuleById(maps.get(i).get("TASK_ID").toString())
, DispatchWork.class);
}
}
CustomerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE);
}
}
DispatchWork.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.pactera.modules.sys.job;
import com.pactera.common.util.SpringContextHolder;
import com.pactera.modules.runscipt.service.RunKettleSerive;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
/**
* @author song
* @date created in 2018-02-01 19:17
*/
public class DispatchWork implements Job {
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
String jobName = jobExecutionContext.getJobDetail().getKey().getName();
String group = jobExecutionContext.getTrigger().getKey().getGroup();
//这样就拿到service了
RunKettleSerive runKettleSerive= SpringContextHolder.getBean(RunKettleSerive.class);
runKettleSerive.runKettleScript(jobName,group);
/* runKettleSerive.runKettleScript(jobName,group);*/
}
}
接口SchedulerUtil,处理调度
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package com.pactera.common.util;
import com.pactera.modules.sys.job.DispatchWork;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
/**
* @author song
* @date created in 2018-01-19 15:35
*/
public class SchedulerUtil {
/**
* 创建定时任务
*
* @param scheduler the scheduler
* @param jobName the job name
* @param jobGroup the job group
* @param cronExpression the cron expression
* @param clazz job class
*/
public static void createScheduleJob(Scheduler scheduler, String jobName, String jobGroup,
String cronExpression, Class<? extends Job> clazz) throws SchedulerException {
//通过schedulerFactory获取一个调度器
SchedulerFactory schedulerfactory=new StdSchedulerFactory();
try{
// 通过schedulerFactory获取一个调度器
scheduler=schedulerfactory.getScheduler();
// 创建jobDetail实例,绑定Job实现类
// 指明job的名称,所在组的名称,以及绑定job类
JobDetail job= JobBuilder.newJob(DispatchWork.class).withIdentity(jobName, jobGroup).build();
Trigger trigger=TriggerBuilder.newTrigger().withIdentity(jobName, jobGroup)
.withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
.startNow().build();
// 把作业和触发器注册到任务调度中
scheduler.scheduleJob(job, trigger);
// 启动调度
scheduler.start();
}catch(Exception e){
e.printStackTrace();
}
}
/**
* 创建定时任务
*
* @param scheduler the scheduler
* @param jobName the job name
* @param jobGroup the job group
* @param cronExpression the cron expression
*/
public static void updateScheduleJob(Scheduler scheduler, String jobName, String jobGroup,
String cronExpression) throws SchedulerException {
TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroup);
//获取trigger,即在spring配置文件中定义的 bean id="myTrigger"
CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
//表达式调度构建器
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
//按新的cronExpression表达式重新构建trigger
try {
trigger = trigger.getTriggerBuilder().withIdentity(triggerKey)
.withSchedule(scheduleBuilder).build();
}catch (Exception e){
System.out.println("errMsg"+e);
return;
}
//按新的trigger重新设置job执行
scheduler.rescheduleJob(triggerKey, trigger);
}
/**
* 暂停任务
*
* @param scheduler the scheduler
* @param jobName the job name
* @param jobGroup the job group
*/
public static void pauseJob(Scheduler scheduler, String jobName, String jobGroup) throws SchedulerException {
JobKey jobKey = JobKey.jobKey(jobName, jobGroup);
scheduler.pauseJob(jobKey);
}
/**
* 恢复任务
*
* @param scheduler the scheduler
* @param jobName the job name
* @param jobGroup the job group
*/
public static void resumeJob(Scheduler scheduler, String jobName, String jobGroup) throws SchedulerException {
JobKey jobKey = JobKey.jobKey(jobName, jobGroup);
scheduler.resumeJob(jobKey);
}
/**
* 删除任务
*
* @param scheduler the scheduler
* @param jobName the job name
* @param jobGroup the job group
*/
public static void deleteJob(Scheduler scheduler, String jobName, String jobGroup) throws SchedulerException {
JobKey jobKey = JobKey.jobKey(jobName, jobGroup);
scheduler.deleteJob(jobKey);
}
/**
* 立即运行
*
* @param scheduler the scheduler
* @param jobName the job name
* @param jobGroup the job group
*/
public static void triggerJob(Scheduler scheduler, String jobName, String jobGroup) throws SchedulerException {
JobKey jobKey = JobKey.jobKey(jobName, jobGroup);
scheduler.triggerJob(jobKey);
}
}
这几天需要用到定时任务调度,因此转向quartz的学习,特此记录下来。

quartz使用起来及其方便,与spring整合配置,只需要写一个类继承QuartzJobBean,重写其executeInternal(JobExecutionContext arg0)即可,我们只需要将自己的逻辑代码写在该方法即可。一旦你配置好实现类并设定好调度时间,Quartz将密切注意剩余时间。当调度程序确定该是执行作业的时候,Quartz框架将调用你作业类上的executeInternal()方法并执行相应的任务。无需报告任何东西给调度器或调用任何特定的东西。仅仅执行任务和结束任务即可。如果配置你的作业在随后再次被调用,Quartz框架将在恰当的时间再次调用它。

quartz有三个核心概念,调度器、任务和触发器。三者关系简单来说就是,调度器负责调度各个任务,到了某个时刻或者过了一定时间,触发器触动了,特定任务便启动执行。概念相对应的类和接口有:

  1)JobDetail:描述任务的相关情况,包括配置任务执行的类和方法。

  2)Trigger:描述出发Job执行的时间触发规则。有SimpleTrigger和CronTrigger两个子类代表两种方式,一种是每隔多少分钟小时执行,则用SimpleTrigger;另一种是日历相关的重复时间间隔,如每天凌晨,每周星期一运行的话,通过Cron表达式便可定义出复杂的调度方案。

  3)Scheduler:代表一个Quartz的独立运行容器,Trigger和JobDetail要注册到Scheduler中才会生效,也就是让调度器知道有哪些触发器和任务,才能进行按规则进行调度任务。
quartz的配置一般有两种,一种是配置无参数的任务,就是一个普通方法,要求该执行任务的方法必须为无参方法,否则会报错。另一种是配置可传参方法,因为这里我需要给任务传递一些参数,所以采用第二种配置方法。

首先,需要下载quartz和spring对其提供支持的jar包。我这里采用的是quartz-2.2.1.jar,spring-context-support-4.2.4.RELEASE.jar,下载其他版本请注意包版本之间的兼容。

title: Spring使用Quartz定时调度Job无法Autowired注入Service的解决方案
tags:

  • Quartz
  • 文章
    categories:
  • Spring
    date: 2018-01-22 13:27:22
    permalink: Spring_Quartz_Job_Autowired

Spring使用Quartz定时调度Job无法Autowired注入Service的解决方案

1. 当时我有个项目要使用调度,所以选择Spring-Quartz,但是遇到了问题就是无法Autowired注入Service。

2. 利用Quartz可以实现定时任务,但在跟Spring整合后,直接在Job中注解方式注入Service后运行却报空指针异常。

原因是Quartz初始化是自己的JobContext,不同于Spring的ApplicationContext,所以无法直接注入

3.具体做法是直接getBean()的方式来获取service的

1
2
3
4
5
6
7
8
9
10
11
public class DispatchWork implements Job {
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
String jobName = jobExecutionContext.getJobDetail().getKey().getName();
String group = jobExecutionContext.getTrigger().getKey().getGroup();
RunKettleSerive runKettleSerive= SpringContextHolder.getBean(RunKettleSerive.class);
runKettleSerive.runKettleScript(jobName,group);
/* runKettleSerive.runKettleScript(jobName,group);*/
}
}

4.关键代码就是RunKettleSerive runKettleSerive= SpringContextHolder.getBean(RunKettleSerive.class)。

后面附上我的spring.xml,Spring-Quartz.xml,和主要的java代码
spring.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd"
default-lazy-init="true">
<description>Spring Configuration</description>
<!-- 加载配置属性文件 -->
<context:property-placeholder ignore-unresolvable="true" location="classpath:config.properties" />
<!-- 加载应用属性实例,在JAVA类中可以 @Value("#{APP_PROP['jdbc.driver']}") 来获取属性文件中jdbc.driver的值 -->
<util:properties id="APP_PROP" location="classpath:config.properties" local-override="true" />
<!-- Controller注解由springMVC扫描 -->
<context:component-scan base-package="com.pactera"><!-- base-package 如果多个,用“,”分隔 -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!--注入spring-quartz-->
<import resource="spring-quartz.xml"/>
</beans>
spring-quartz.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
">
<!-- 配置调度器工厂(SchedulerFactoryBean) -->
<bean name="startQuertz"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="myJobTrigger" />
</list>
</property>
</bean>
<!-- 配置Cron触发器(CronTriggerFactoryBean) -->
<bean id="myJobTrigger"
class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail">
<ref bean="myJobDetail" />
</property>
<property name="cronExpression">
<!-- 每隔10分钟执行 -->
<value>0 0/2 * * * ?</value>
<!-- <value>0/20 * * * * ?</value> -->
<!-- 每隔2小时 <value>* * */2 * * ?</value> -->
</property>
</bean>
<!-- 配置方法调用任务工厂(XXXJobDetailFactoryBean) -->
<bean id="myJobDetail"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject">
<ref bean="myJob" />
</property>
<property name="targetMethod">
<value>doWork</value>
</property>
</bean>
<!-- 工作的bean -->
<bean id="myJob" class="com.pactera.modules.sys.job.DispatchJob" lazy-init="true">
</bean>
<!--&lt;!&ndash; 工作的bean &ndash;&gt;
<bean id="myJob2" class="com.pactera.modules.sys.job.DispatchWork" lazy-init="true">
<property name="runKettleSerive" >
<ref bean="unKettleSeriveImpl" />
</property>
</bean>-->
</beans>
DispatchJob.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import com.pactera.common.support.CustomerContextHolder;
import com.pactera.common.util.SchedulerUtil;
import com.pactera.modules.datadistribute.services.DistributeShellService;
import com.pactera.modules.distribute.service.DistributeWorkInfoService;
import com.pactera.modules.runscipt.service.RunKettleSerive;
import com.pactera.modules.runscipt.service.RunScriptService;
import com.pactera.modules.settings.service.DamDependencyService;
import com.pactera.modules.settings.service.DamFrequencyService;
import com.pactera.modules.settings.service.DamVariableDatadateService;
import org.apache.log4j.Logger;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* Created by echo_ on 2017/12/8.
* @author sxl
*/
public class DispatchJob {
private static final Logger logger = Logger.getLogger(DispatchJob.class);
@Autowired
private DamVariableDatadateService damVariableDatadateService;
@Autowired
private DistributeShellService distributeShellService;
@Autowired
private DistributeWorkInfoService distributeWorkInfoService;
@Autowired
private RunScriptService runScriptService;
@Autowired
private RunKettleSerive runKettleScript;
@Autowired
private DamDependencyService damDependencyService;
@Autowired
private DamFrequencyService damFrequencyService;
public void doWork() throws SchedulerException {
doShellWork();
System.out.println(new Date());
}
public void doShellWork() throws SchedulerException {
CustomerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE_DAM);
List<Map<String, Object>> maps = distributeShellService.selectDistributeTask();
SchedulerFactory schedulerfactory = new StdSchedulerFactory();
Scheduler scheduler = schedulerfactory.getScheduler();
for (int i=0;i<maps.size();i++){
List<String> wid_List = Arrays.asList(StringUtils.commaDelimitedListToStringArray(maps.get(i).get("WORK_ID").toString()));
//作业idlist
for (int k=0;k<wid_List.size();k++){
SchedulerUtil.createScheduleJob(scheduler, maps.get(i).get("TASK_ID").toString(), wid_List.get(k), damFrequencyService.selectTriggerRuleById(maps.get(i).get("TASK_ID").toString())
, DispatchWork.class);
}
}
CustomerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE);
}
}
DispatchWork.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.pactera.modules.sys.job;
import com.pactera.common.util.SpringContextHolder;
import com.pactera.modules.runscipt.service.RunKettleSerive;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
/**
* @author song
* @date created in 2018-02-01 19:17
*/
public class DispatchWork implements Job {
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
String jobName = jobExecutionContext.getJobDetail().getKey().getName();
String group = jobExecutionContext.getTrigger().getKey().getGroup();
//这样就拿到service了
RunKettleSerive runKettleSerive= SpringContextHolder.getBean(RunKettleSerive.class);
runKettleSerive.runKettleScript(jobName,group);
/* runKettleSerive.runKettleScript(jobName,group);*/
}
}
接口SchedulerUtil,处理调度
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package com.pactera.common.util;
import com.pactera.modules.sys.job.DispatchWork;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
/**
* @author song
* @date created in 2018-01-19 15:35
*/
public class SchedulerUtil {
/**
* 创建定时任务
*
* @param scheduler the scheduler
* @param jobName the job name
* @param jobGroup the job group
* @param cronExpression the cron expression
* @param clazz job class
*/
public static void createScheduleJob(Scheduler scheduler, String jobName, String jobGroup,
String cronExpression, Class<? extends Job> clazz) throws SchedulerException {
//通过schedulerFactory获取一个调度器
SchedulerFactory schedulerfactory=new StdSchedulerFactory();
try{
// 通过schedulerFactory获取一个调度器
scheduler=schedulerfactory.getScheduler();
// 创建jobDetail实例,绑定Job实现类
// 指明job的名称,所在组的名称,以及绑定job类
JobDetail job= JobBuilder.newJob(DispatchWork.class).withIdentity(jobName, jobGroup).build();
Trigger trigger=TriggerBuilder.newTrigger().withIdentity(jobName, jobGroup)
.withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
.startNow().build();
// 把作业和触发器注册到任务调度中
scheduler.scheduleJob(job, trigger);
// 启动调度
scheduler.start();
}catch(Exception e){
e.printStackTrace();
}
}
/**
* 创建定时任务
*
* @param scheduler the scheduler
* @param jobName the job name
* @param jobGroup the job group
* @param cronExpression the cron expression
*/
public static void updateScheduleJob(Scheduler scheduler, String jobName, String jobGroup,
String cronExpression) throws SchedulerException {
TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroup);
//获取trigger,即在spring配置文件中定义的 bean id="myTrigger"
CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
//表达式调度构建器
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
//按新的cronExpression表达式重新构建trigger
try {
trigger = trigger.getTriggerBuilder().withIdentity(triggerKey)
.withSchedule(scheduleBuilder).build();
}catch (Exception e){
System.out.println("errMsg"+e);
return;
}
//按新的trigger重新设置job执行
scheduler.rescheduleJob(triggerKey, trigger);
}
/**
* 暂停任务
*
* @param scheduler the scheduler
* @param jobName the job name
* @param jobGroup the job group
*/
public static void pauseJob(Scheduler scheduler, String jobName, String jobGroup) throws SchedulerException {
JobKey jobKey = JobKey.jobKey(jobName, jobGroup);
scheduler.pauseJob(jobKey);
}
/**
* 恢复任务
*
* @param scheduler the scheduler
* @param jobName the job name
* @param jobGroup the job group
*/
public static void resumeJob(Scheduler scheduler, String jobName, String jobGroup) throws SchedulerException {
JobKey jobKey = JobKey.jobKey(jobName, jobGroup);
scheduler.resumeJob(jobKey);
}
/**
* 删除任务
*
* @param scheduler the scheduler
* @param jobName the job name
* @param jobGroup the job group
*/
public static void deleteJob(Scheduler scheduler, String jobName, String jobGroup) throws SchedulerException {
JobKey jobKey = JobKey.jobKey(jobName, jobGroup);
scheduler.deleteJob(jobKey);
}
/**
* 立即运行
*
* @param scheduler the scheduler
* @param jobName the job name
* @param jobGroup the job group
*/
public static void triggerJob(Scheduler scheduler, String jobName, String jobGroup) throws SchedulerException {
JobKey jobKey = JobKey.jobKey(jobName, jobGroup);
scheduler.triggerJob(jobKey);
}
}
这几天需要用到定时任务调度,因此转向quartz的学习,特此记录下来。

quartz使用起来及其方便,与spring整合配置,只需要写一个类继承QuartzJobBean,重写其executeInternal(JobExecutionContext arg0)即可,我们只需要将自己的逻辑代码写在该方法即可。一旦你配置好实现类并设定好调度时间,Quartz将密切注意剩余时间。当调度程序确定该是执行作业的时候,Quartz框架将调用你作业类上的executeInternal()方法并执行相应的任务。无需报告任何东西给调度器或调用任何特定的东西。仅仅执行任务和结束任务即可。如果配置你的作业在随后再次被调用,Quartz框架将在恰当的时间再次调用它。

quartz有三个核心概念,调度器、任务和触发器。三者关系简单来说就是,调度器负责调度各个任务,到了某个时刻或者过了一定时间,触发器触动了,特定任务便启动执行。概念相对应的类和接口有:

  1)JobDetail:描述任务的相关情况,包括配置任务执行的类和方法。

  2)Trigger:描述出发Job执行的时间触发规则。有SimpleTrigger和CronTrigger两个子类代表两种方式,一种是每隔多少分钟小时执行,则用SimpleTrigger;另一种是日历相关的重复时间间隔,如每天凌晨,每周星期一运行的话,通过Cron表达式便可定义出复杂的调度方案。

  3)Scheduler:代表一个Quartz的独立运行容器,Trigger和JobDetail要注册到Scheduler中才会生效,也就是让调度器知道有哪些触发器和任务,才能进行按规则进行调度任务。
quartz的配置一般有两种,一种是配置无参数的任务,就是一个普通方法,要求该执行任务的方法必须为无参方法,否则会报错。另一种是配置可传参方法,因为这里我需要给任务传递一些参数,所以采用第二种配置方法。
首先,需要下载quartz和spring对其提供支持的jar包。我这里采用的是quartz-2.2.1.jar,spring-context-support-4.2.4.RELEASE.jar,下载其他版本请注意包版本之间的兼容。

×

纯属好玩

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

文章目录
  1. 1. Spring使用Quartz定时调度Job无法Autowired注入Service的解决方案
    1. 1.1. 1. 当时我有个项目要使用调度,所以选择Spring-Quartz,但是遇到了问题就是无法Autowired注入Service。
    2. 1.2. 2. 利用Quartz可以实现定时任务,但在跟Spring整合后,直接在Job中注解方式注入Service后运行却报空指针异常。
    3. 1.3. 3.具体做法是直接getBean()的方式来获取service的
  2. 2. 4.关键代码就是RunKettleSerive runKettleSerive= SpringContextHolder.getBean(RunKettleSerive.class)。
    1. 2.0.0.1. 后面附上我的spring.xml,Spring-Quartz.xml,和主要的java代码
    2. 2.0.0.2. spring.xml
    3. 2.0.0.3. spring-quartz.xml
    4. 2.0.0.4. DispatchJob.java
  3. 2.0.1. DispatchWork.java
    1. 2.0.1.1. 接口SchedulerUtil,处理调度
    2. 2.0.1.2. 这几天需要用到定时任务调度,因此转向quartz的学习,特此记录下来。
    3. 2.0.1.3. quartz有三个核心概念,调度器、任务和触发器。三者关系简单来说就是,调度器负责调度各个任务,到了某个时刻或者过了一定时间,触发器触动了,特定任务便启动执行。概念相对应的类和接口有:
  • 首先,需要下载quartz和spring对其提供支持的jar包。我这里采用的是quartz-2.2.1.jar,spring-context-support-4.2.4.RELEASE.jar,下载其他版本请注意包版本之间的兼容。
    1. 1. Spring使用Quartz定时调度Job无法Autowired注入Service的解决方案
      1. 1.1. 1. 当时我有个项目要使用调度,所以选择Spring-Quartz,但是遇到了问题就是无法Autowired注入Service。
      2. 1.2. 2. 利用Quartz可以实现定时任务,但在跟Spring整合后,直接在Job中注解方式注入Service后运行却报空指针异常。
      3. 1.3. 3.具体做法是直接getBean()的方式来获取service的
    2. 2. 4.关键代码就是RunKettleSerive runKettleSerive= SpringContextHolder.getBean(RunKettleSerive.class)。
      1. 2.0.0.1. 后面附上我的spring.xml,Spring-Quartz.xml,和主要的java代码
      2. 2.0.0.2. spring.xml
      3. 2.0.0.3. spring-quartz.xml
      4. 2.0.0.4. DispatchJob.java
    3. 2.0.1. DispatchWork.java
      1. 2.0.1.1. 接口SchedulerUtil,处理调度
      2. 2.0.1.2. 这几天需要用到定时任务调度,因此转向quartz的学习,特此记录下来。
      3. 2.0.1.3. quartz有三个核心概念,调度器、任务和触发器。三者关系简单来说就是,调度器负责调度各个任务,到了某个时刻或者过了一定时间,触发器触动了,特定任务便启动执行。概念相对应的类和接口有:
  • 首先,需要下载quartz和spring对其提供支持的jar包。我这里采用的是quartz-2.2.1.jar,spring-context-support-4.2.4.RELEASE.jar,下载其他版本请注意包版本之间的兼容。
    1. 1. Spring使用Quartz定时调度Job无法Autowired注入Service的解决方案
      1. 1.1. 1. 当时我有个项目要使用调度,所以选择Spring-Quartz,但是遇到了问题就是无法Autowired注入Service。
      2. 1.2. 2. 利用Quartz可以实现定时任务,但在跟Spring整合后,直接在Job中注解方式注入Service后运行却报空指针异常。
      3. 1.3. 3.具体做法是直接getBean()的方式来获取service的
    2. 2. 4.关键代码就是RunKettleSerive runKettleSerive= SpringContextHolder.getBean(RunKettleSerive.class)。
      1. 2.0.0.1. 后面附上我的spring.xml,Spring-Quartz.xml,和主要的java代码
      2. 2.0.0.2. spring.xml
      3. 2.0.0.3. spring-quartz.xml
      4. 2.0.0.4. DispatchJob.java
    3. 2.0.1. DispatchWork.java
      1. 2.0.1.1. 接口SchedulerUtil,处理调度
      2. 2.0.1.2. 这几天需要用到定时任务调度,因此转向quartz的学习,特此记录下来。
      3. 2.0.1.3. quartz有三个核心概念,调度器、任务和触发器。三者关系简单来说就是,调度器负责调度各个任务,到了某个时刻或者过了一定时间,触发器触动了,特定任务便启动执行。概念相对应的类和接口有:
  • ,