SpringBoot integrate Quartz Timing

Background
In a recent project, a project there is a demand: the need to use regular tasks, the timing of this task requires effective immediately.
After viewing the official website found Quartz: Quartz offers two basic job-storage type:

RAMJobStore: RAM memory, i.e., the default will Quartz task scheduling in the presence of a memory, the best performance in this way, since the memory speed is the fastest. Bad part was the lack of data persistence, but the program crashes or when re-released, all running information will be lost
JDBC Job Storage: After saved to the database, you can do a single point can also do cluster, when the task is more, can be unified management. Shut down or reboot the server, running the information will not be lost. Drawback is that the speed depends on how fast speed connection to the database.
So we decided to use JDBC operations storage mode.

Why persist?
Clusters can be done later.
Tasks can be managed at any time to stop, pause, modify tasks.
You should understand the concept
because before the contact with quartz task scheduling framework, so there is a certain understanding of quartz, quartz three elements: Scheduler, Trigger, JobDetai & Job .
Suddenly I think of it, written before the introduction -. - forget how, paste the address, you need to understand children's shoes can go to the next:
https://blog.csdn.net/bicheng4769/article/details/81097305

SpringBoot integrated Quartz
we can go together to integrate quartz and springBoot, in fact, that is springBoot as it is sping, because we do not have a shortcut to the related spirngboot used.
If you want to quickly integrate Quartz children's shoes, and immediately see the effect, you can turn straight down, looking directly at SpirngBoot Quartz comes with plug-ins. But I suggest that you start from the spring to integrate Quartz, understand the principle of rewarding party.

Quartz initialization table
if you need to do persist, then the data is to be sure there is a database, what tables exist then in the end it? In fact, the document's official website also talked with us at the following address:
http://www.quartz-scheduler.org/documentation/quartz-2.2.x/tutorials/tutorial-lesson-09.html
which there is a saying:

JDBCJobStore works with nearly any database, it has been used widely with Oracle, PostgreSQL, MySQL, MS SQLServer, HSQLDB, and DB2. To use JDBCJobStore, you must first create a set of database tables for Quartz to use. You can find table-creation SQL scripts in the “docs/dbTables” directory of the Quartz distribution.

Rong old lady to you this level four of the Translation:
probably support so many database types. If you want to use JDBCJoBStore, you must first create some tables that the "doc / dbTables" inside. "Doc / dbTables" Where is it? In fact, there are source, directly to the official website down the line.

Spring integrate the Quartz
POM jar file to the relevant
configuration file (either properties or yml. Using JDBC store)
business logic layer in use.
pom file
as follows:

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--quartz -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz-jobs</artifactId>
<!- <Version> 2.3.0 </ Version> -> <dependency><-! Timer task context module relies ->
</ dependency>


<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<Version> 0.9.5.2 </ Version>
</ dependency>
<- & lt;! & ndash; ndash Druid database connection pool &; & gt; -!>
<dependency>
<the groupId> com.alibaba </ the groupId>
<the artifactId> Spring-Boot--Druid Starter </ the artifactId>
<Version> 1.1.10 </ Version>
</ dependency>
</ Dependencies>
corresponding properties file
# use its own configuration file
org.quartz.jobStore.useProperties: true

# Default or changed their name will do
org.quartz.scheduler.instanceName: DefaultQuartzScheduler
# If you are using clusters, instanceId must be unique, set to AUTO
org.quartz.scheduler.instanceId = AUTO


org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount: 10
org.quartz.threadPool.threadPriority: 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread: true


# Storage use JobStoreTX, that is, the database
org.quartz.jobStore.class: org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelegate
# whether to use a cluster (if the project only deployed to a server, would not have)
org.quartz.jobStore.isClustered = false
org.quartz.jobStore.clusterCheckinInterval = 20000
org.quartz.jobStore.tablePrefix = qrtz_
org.quartz.jobStore.dataSource = myDS

Configuration data source #
# database table name prefix table quartz
org.quartz.dataSource.myDS.driver = com.mysql.jdbc.Driver
org.quartz.dataSource.myDS.URL = JDBC: MySQL: // localhost: 3306 / serverTimezone = & characterEncoding GMT aipyun = UTF-8?
org.quartz.dataSource.myDS.user = root
org.quartz.dataSource.myDS.password = root123
org.quartz.dataSource.myDS.maxConnections = 5
core QuartzConfiguration categories:
ackage com.cj .config;

import org.quartz.Scheduler;
import org.quartz.spi.JobFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

/ **
* Description: quartz configuration
*
* @author Caojing
* @Create 2018-12-24-16: 47
* /
@Configuration
public class QuartzConfiguration {
@Autowired
Private JobFactory JobFactory;

@Bean
public SchedulerFactoryBean the SchedulerFactoryBean () {
the SchedulerFactoryBean SchedulerFactoryBean the SchedulerFactoryBean new new = ();
schedulerFactoryBean.setJobFactory (JobFactory);
// for cluster quartz, update already present when QuartzScheduler Job Start
schedulerFactoryBean.setOverwriteExistingJobs (to true);
// start extended
SchedulerFactoryBean .setStartupDelay (. 1);
// set the load profile
schedulerFactoryBean.setConfigLocation (a ClassPathResource new new ( "/ the quartz.properties"));
return SchedulerFactoryBean;
}

@Bean
public Scheduler Scheduler () {
. SchedulerFactoryBean return () the getScheduler ();
}
}
which we initialize class 2 moved the IOC, because before Quartz instantiated to control their own, why do later there will be talked about.
SchedulerFactoryBean is a class that is actually before the xml configuration SchedulerFactoryBean. Before attaching xml configuration is as follows (no need to configure here, springboot suggested that we use less configuration xml)

<the bean class = "org.springframework.scheduling.quartz.SchedulerFactoryBean">
<Property name = "Triggers">
<List>
<REF = the bean "oceanStatusCronTrigger" />
</ List>
</ Property>
</ the bean>
class I believe that if people used the xml configuration must be very familiar with, which is Quartz entrance. And also a bridge spring Scheduler relations. So, Scheduler automatically start to work after the Spring container startup, before the Spring container is closed, shut down automatically Scheduler.

JobFactory类
package com.cj.config;

import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.quartz.AdaptableJobFactory;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;
import org.springframework.stereotype.Component;

/**
* 描述:
*
* @author caojing
* @create 2018-12-26-14:03
*/
@Component
public class JobFactory extends AdaptableJobFactory {

@Autowired
private AutowireCapableBeanFactory capableBeanFactory;


@Override
protected Object createJobInstance (Final TriggerFiredBundle the bundle) throws Exception {
// call the parent class method
Object jobInstance = super.createJobInstance (the bundle);
// for injection
capableBeanFactory.autowireBean (jobInstance);
; return jobInstance
}
}
action of this class Job was speaking to instantiate IOC to carry out.
In fact, the problem is:
Examples of process Job objects is carried out in Quartz, the entity class is injected in the job can not be injected so that the entity classes Srping Spring container among containers.
Solution: Job Bean also incorporated into the Spring container management, Spring containers can naturally good for the Job Bean needed to rely on automated assembly.
How to incorporate: Job creation is created by JobFactory. Official website interpreted as evidence:
https://www.quartz-scheduler.org/api/2.2.1/org/quartz/spi/JobFactory.html

A JobFactory is responsible for producing instances of Job classes.

Translation: JobFactory responsible for generating the instance of the Job class.
There are two implementation class JobFactory: AdaptableJobFactory and SimpleJobFactory.

JobFactory factory custom classes inherit AdaptableJobFactory.
Job instantiate achieved by calling the parent class AdaptableJobFactory method createJobInstance.
After Job End of example, and then calls itself to automatic assembly methods for the created attribute instance Job management and incorporated into Spring container. (Incorporated by AutowireCapableBeanFactory). Hu cut ~ ~ ~ ~
UploadTask categories:
Package Penalty for com.cj.quartzdemo;
Import com.cj.controller.IndexController;
Import org.quartz.DisallowConcurrentExecution;
Import org.quartz.JobExecutionContext;
Import org.quartz.JobExecutionException;
Import org.springframework .beans.factory.annotation.Autowired;
Import org.springframework.scheduling.quartz.QuartzJobBean;
Import org.springframework.stereotype.Component;
Import org.springframework.stereotype.Service;

import java.util.Date;

/**
* 描述:
*
* @author caojing
* @create 2018-12-25-11:38
*/
@Component
@DisallowConcurrentExecution
public class UploadTask extends QuartzJobBean {
@Autowired
private IndexController indexController;
@Override
protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println(new Date() + "任务开始------------------------------------");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(new Date() + "任务结束------------------------------------");
}
}


Inherit QuartzJobBean class, override executeInternal method.
Annex: DisallowConcurrentExecution job execution such as 10 seconds, the task is executed every 5 seconds, with the annotation, the program will execute the next task after the other end 10 seconds.

indexController类:
package com.cj.controller;

import com.cj.quartzdemo.UploadTask;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
* 描述:
*
* @author caojing
* @create 2018-12-26-14:11
*/
@Controller
public class IndexController {
@Autowired
private Scheduler scheduler;

@ RequestMapping (value = "/ index", Method, = RequestMethod.GET)
public void index () throws SchedulerException {
// cron expression
CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule ( "0/8 * * * *?");
// Get the name and identity of the current group trgger according
triggerKey triggerKey = TriggerKey.triggerKey ( "CJ", "123");
a CronTrigger triggerOld = null;
the try {
// trigger information acquired
triggerOld = (CronTrigger) scheduler.getTrigger (triggerKey ) ;
} the catch (SchedulerException E) {
e.printStackTrace ();
}
IF (triggerOld == null) {
// the job is added to the jobDetail
jobDetail jobDetail = JobBuilder.newJob (UploadTask.class) .withIdentity ( "cj", " . 123 ") build ();
Trigger trigger = TriggerBuilder.newTrigger().withIdentity("cj","123").withSchedule(cronScheduleBuilder).build();
//执行任务
scheduler.scheduleJob(jobDetail, trigger);
} else {
System.out.println("当前job已存在--------------------------------------------");
}
}
}

Browser and enter http: // localhost: 8080 / index, we can see our database has stored the write cron expressions and corresponding class.
View database tables (qrtz_cron_triggers) Attach screenshot:


So far, job we have been successfully persisted to the database. Let's look back at the whole of a process.

pom file to add the corresponding dependencies.
mysql database corresponding to the initialization table.
Configuration corresponding properties
of the original quartz control class to instantiate spirng IOC control. (Corresponding to the core classes and QuartzConfiguration JobFactory based)
business logic for job control.
Summarize
actually thinking tidy, we found that the process is actually quite simple, the only difficulty is that there may be some understanding of QuartzConfiguration JobFactory class and class. Both classes also integrate core classes.
But after springboot2.0, I found a very magical starter.

Guess you like

Origin www.cnblogs.com/itboxue/p/12387423.html