- 1. Import dependencies:
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>
- 2. Add to ProjectQuartz.propertiesFile (so you don't have to walk its own properties file)
#quartz cluster configuration
# ===========================================================================
# Configure Main Scheduler Properties Scheduler Properties
# ===========================================================================
#Each instance in the dispatch identity name cluster must have the same name
org.quartz.scheduler.instanceName=DefaultQuartzScheduler
#ID set to get each one automatically must be different
org.quartz.scheduler.instanceid=AUTO
#============================================================================
# Configure ThreadPool
#============================================================================
#Implementation class for thread pools (SimpleThreadPool is typically used to meet almost all user needs)
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
#Specify the number of threads, at least 1 (no default) (generally set to a direct integer of 1-100 is appropriate)
org.quartz.threadPool.threadCount = 5
#Set thread priority (max.java.lang.Thread.MAX_PRIORITY 10, min.Thread.MIN_PRIORITY 1, default 5)
org.quartz.threadPool.threadPriority = 5
#============================================================================
# Configure JobStore
#============================================================================
# Information save time default 60 seconds
org.quartz.jobStore.misfireThreshold = 60000
#Data is saved as a database persistence
org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
#Database proxy class, generalOrg.quartz.impl.Jdbcjobstore.StdJDBCDelegateCan satisfy most databases
org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate
#Use your own profile
org.quartz.jobStore.useProperties = true
#Database Aliases are freely available
org.quartz.jobStore.dataSource = myDS
#Table prefix, default QRTZ_
org.quartz.jobStore.tablePrefix = qrtz_
#Whether to join a cluster
org.quartz.jobStore.isClustered = false
#Check interval for scheduling instance failures
org.quartz.jobStore.clusterCheckinInterval = 20000
#============================================================================
# Configure Datasources
#============================================================================
#database engine
org.quartz.dataSource.myDS.driver = com.mysql.jdbc.Driver
#Database Connection
org.quartz.dataSource.myDS.URL = jdbc:mysql://127.0.0.1:3306/quartz?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowMultiQueries=true
#Database User
org.quartz.dataSource.myDS.user = root
#Database Password
org.quartz.dataSource.myDS.password = cym
#Allow maximum connections
org.quartz.dataSource.myDS.maxConnections = 50
#Validate query sql, can not be set
#org.quartz.dataSource.myDS.validationQuery=select 0 from dual
-
3. Create quartz-related tables in the database
Enter quartz's official website http://www.quartz-scheduler.org/ , click Downloads, and after downloading, there is a script for creating quartz tables from a common database under the directory \docs\dbTables.
-
4. Register related bean s
- Customize the AutowiringSpringBeanJobFactory to solve the problem that spring cannot inject bean s into quartz
package com.cci.eclickup.common.configuration.quartz;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;
/**
* @Author: Kingcym
* @Description:
* @Date: 2017/12/14 0:31
*/
public final class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements
ApplicationContextAware {
private transient AutowireCapableBeanFactory beanFactory;
@Override
public void setApplicationContext(final ApplicationContext context) {
beanFactory = context.getAutowireCapableBeanFactory();
}
@Override
protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
final Object job = super.createJobInstance(bundle);
beanFactory.autowireBean(job);
return job;
}
}
Register bean s for SchedulerFactoryBean
package com.cci.eclickup.common.configuration.quartz;
import org.quartz.spi.JobFactory;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import java.util.Properties;
/**
* @Author: Kingcym
* @Description:
* @Date: 2017/12/13 23:45
*/
@Configuration
public class QuartzConfig {
public static final String QUARTZ_PROPERTIES_PATH = "/quartz.properties";
@Bean
public JobFactory jobFactory(ApplicationContext applicationContext) {
AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
jobFactory.setApplicationContext(applicationContext);
return jobFactory;
}
@Bean
public SchedulerFactoryBean schedulerFactoryBean( JobFactory jobFactory) {
SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
schedulerFactoryBean.setJobFactory(jobFactory);
schedulerFactoryBean.setStartupDelay(20);
//For quartz cluster, load quartz data source configuration
schedulerFactoryBean.setQuartzProperties(quartzProperties());
return schedulerFactoryBean;
}
public Properties quartzProperties(){
PropertiesFactoryBean factoryBean = new PropertiesFactoryBean();
factoryBean.setLocation(new ClassPathResource(QUARTZ_PROPERTIES_PATH));
try {
factoryBean.afterPropertiesSet();
return factoryBean.getObject();
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}
Define JobDetail, Trigger
package com.cci.eclickup.common.configuration.quartz;
import com.cci.eclickup.cn.task.CheckStatusTask;
import com.cci.eclickup.cn.task.InsertEvaluateTask;
import org.apache.log4j.Logger;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import static org.quartz.CronScheduleBuilder.cronSchedule;
/**
* @Author: Kingcym
* @Description:
* @Date: 2017/12/14 0:14
*/
@Component
public class QuartzScheduler {
@SuppressWarnings("SpringJavaAutowiringInspection")
@Autowired
private SchedulerFactoryBean schedulerFactoryBean;
private Logger logger = Logger.getLogger(QuartzScheduler.class);
@PostConstruct
public void init() throws SchedulerException {
scheduleJobs();
}
public void scheduleJobs() throws SchedulerException {
logger.info("=======Task Initialization========");
Scheduler scheduler = schedulerFactoryBean.getScheduler();
//To transfer data, use JobDataMa
// JobDataMap jobDataMap = new JobDataMap();
// jobDataMap.put("jobArg", "world");
//CheckStatusTask.class Is the class name that needs to perform a timed task
JobDetail jobDetail = JobBuilder.newJob(CheckStatusTask.class)
// .setJobData(jobDataMap)
.withDescription("CheckStatusTask")
.withIdentity("job-CheckStatus", "demo-group")
.build();
//InsertEvaluateTask.class Is the class name that needs to perform a timed task
JobDetail jobDetail2 = JobBuilder.newJob(InsertEvaluateTask.class)
// .setJobData(jobDataMap)
.withDescription("InsertEvaluateTask")
.withIdentity("job-InsertEvaluate", "demo-group")
.build();
Trigger trigger = TriggerBuilder.newTrigger()
.forJob(jobDetail)
.withSchedule(cronSchedule("0 0/2 * * * ? "))
.build();
Trigger trigger2 = TriggerBuilder.newTrigger()
.forJob(jobDetail2)
.withSchedule(cronSchedule("0 0/1 * * * ? "))
.build();
try {
if(!scheduler.checkExists(JobKey.jobKey("job-CheckStatus","demo-group"))){
scheduler.scheduleJob(jobDetail,trigger);
}
if(!scheduler.checkExists(JobKey.jobKey("job-InsertEvaluate","demo-group"))){
scheduler.scheduleJob(jobDetail2,trigger2);
}
scheduler.start();
logger.info("=======Task Initialization Completed========");
} catch (SchedulerException e) {
e.printStackTrace();
}
}
}
- 5 Define a timer task by inheriting the Job interface and implementing the execute method
package com.cci.eclickup.cn.task;
import com.cci.eclickup.cn.service.EclickupService;
import org.apache.log4j.Logger;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @Description: Refresh z_periodicallyCheck_checkStatus in evaluate
* @author cym
* @date 2017 December 14, 12:04:40 a.m.
* @version V1.0
*/
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
@Component
public class CheckStatusTask implements Job {
private Logger log = Logger.getLogger(CheckStatusTask.class);
@Autowired
private EclickupService eclickupService;
public void execute(JobExecutionContext context) throws JobExecutionException {
log.info("===============Timed refresh z_check_evaluate In checkStatus start==============");
int result = eclickupService.editCheckStatus();
if (result > 0)
log.info("===============Timed refresh z_check_evaluate In checkStatus Success==============Number:"+result);
}
}
More information: http://blog.csdn.net/growing_duck/article/details/75115913
http://blog.csdn.net/convict_eva/article/details/52486208
http://blog.csdn.net/u011687186/article/details/62215934
http://www.quartz-scheduler.org/downloads/
http://blog.csdn.net/KokJuis/article/details/78526709
https://icecarev.com/2016/11/05/spring-boot-1-4-and-quartz-scheduling-runtime-created-job-instances-from-a-configuration-file/
http://blog.csdn.net/hj7jay/article/details/50771559