Spring integrates Quartz's simple configuration approach

  • 2020-06-01 09:47:13
  • OfStack

In practice, however, it is rarely used directly. The spring-quartz component is usually used, and is configured directly so that the spring framework can be assembled automatically
Here's how the spring framework integrates quartz components to configure timed tasks

1. Maven dependency


<dependency> 
  <groupId>org.springframework</groupId> 
  <artifactId>spring-context-support</artifactId> 
  <version>4.0.5.RELEASE</version> 
</dependency> 
<dependency> 
  <groupId>org.quartz-scheduler</groupId> 
  <artifactId>quartz</artifactId> 
  <version>2.2.1</version> 
</dependency> 

The quartz package is the core package, which is responsible for the implementation of timing tasks. The spring-context-support package includes spring to quartz integration tools

2. Spring configuration


<bean id="task" class="..."></bean> 
<bean id="job" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> 
  <property name="targetObject" ref="task" /> 
  <property name="targetMethod" value="run" /> 
</bean> 
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean"> 
  <property name="jobDetail" ref="job" /> 
  <property name="cronExpression" value="0 0 0 * * ?" /> 
</bean> 
<bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> 
  <property name="triggers"> 
    <list> 
      <ref bean="cronTrigger" /> 
    </list> 
  </property> 
  <property name="autoStartup" value="true" /> 
</bean> 

The configuration of spring to quartz consists of four steps:

Configure the actual execution of the business logic class, which is the normal spring bean
Configure the JobDetail class, MethodInvokingJobDetailFactoryBean in the example above, which needs to specify the bean that performs the business logic and the method name to invoke
Configure the Trigger (task triggering) class, CronTriggerFactoryBean in the example above, to fire the task based on the cron expression and specify the JobDetail and cron expressions
Configuring the scheduler (timed task) class, SchedulerFactoryBean in the example above, is to register trigger in the timed task for trigger to take effect

The above is an example of a task that is invoked on a basic method and a timed task that is triggered based on an cron expression, which is also mostly used in Java Web projects


Related articles: