1:maven仓库导入:
- <dependency>
- <groupId>org.quartz-scheduler</groupId>
- <artifactId>quartz</artifactId>
- <version>2.2.1</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context-support</artifactId>
- <version>${project.spring.version}</version>
- </dependency>
注意上面<version>${project.spring.version}</version>是写和spring版本一样
2:新建一个名为spring-quartz.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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd ">
<bean id="job" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass" value="com.cdhy.automobile.quartz.PromotionJob"></property>
</bean>
<bean id="trg" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="job"/>
<property name="cronExpression">
<value>10,15 * * * * ?</value>
</property>
</bean>
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="jobFactory" ref="f"></property>
<property name="triggers">
<list>
<ref bean="trg"/>
</list>
</property>
</bean>
</beans>
注意上面 <value>10,15 * * * * ?</value>是配置定时器开始启动的时间代码
咋个弄可以参考这个https://blog.csdn.net/zdx1515888659/article/details/79158169
注意
3:在SPRING.xml(applicationontext.xml)文件里面配置注入:
<import resource="spring-quartz.xml" />
还要有包扫描(注意包路径)
<context:component-scan base-package="com.cdhy.automobile"></context:component-scan>
4:在包路径下新建一个JobFactory
写入:
@Service("f")
public class JobFactory extends AdaptableJobFactory {
@Autowired
private AutowireCapableBeanFactory capableBeanFactory;
@Override
protected Object createJobInstance(TriggerFiredBundle bundle)
throws Exception {
Object jobInstance = super.createJobInstance(bundle);
capableBeanFactory.autowireBean(jobInstance);
return jobInstance;
}
5:在包路径下新建PromotionJob
写入:public class PromotionJob implements Job{
@Autowired
private IInvoiceService invoiceServiceImpl;
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
System.out.println("quartz执行");
invoiceServiceImpl.updateDB(new Date());
}
其中 @Autowired
private IInvoiceService invoiceServiceImpl;是要在具体的方法里面做处理注入的一个服务