java quartz 配置,Spring Boot 2.0 整合Quartz Java代码配置方式例子

学习配置

项目概述和结构

在这个带有Quartz例的Spring Boot 批处理中,我们将创建两个具有不同步数的不同批处理作业。然后我们将使用夸脱作业数据映射和触发器计划作业执行,并在控制台中观察输出。

b48f1364a7c4c0a5cd50d8ba75f5f80c.png

Maven依赖

Spring引导内置了对quartz的支持,所以你只需要导入依赖项,比如spring-boot-starter-quartz和spring-boot-starter-batch。

请注意,quartz至少需要一个可用于存储作业执行详细信息的数据库。在这个例子中,我使用H2Spring引导支持的数据库。所以包括'h2'依赖性。

pom.xml

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0

com.howtodoinjava

App

0.0.1-SNAPSHOT

jar

App

http://maven.apache.org

org.springframework.boot

spring-boot-starter-parent

2.0.3.RELEASE

UTF-8

org.springframework.boot

spring-boot-starter-batch

org.springframework.boot

spring-boot-starter-quartz

com.h2database

h2

runtime

org.springframework.boot

spring-boot-maven-plugin

repository.spring.release

Spring GA Repository

http://repo.spring.io/release

创建具有多个任务的批处理作业

创建Tasklet

首先创建几个tasklet。这些是在单批作业中的步骤中处理的策略。

MyTaskOne.java

import org.springframework.batch.core.StepContribution;

import org.springframework.batch.core.scope.context.ChunkContext;

import org.springframework.batch.core.step.tasklet.Tasklet;

import org.springframework.batch.repeat.RepeatStatus;

public class MyTaskOne implements Tasklet {

public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {

System.out.println("MyTaskOne start..");

// ... your code

System.out.println("MyTaskOne done..");

return RepeatStatus.FINISHED;

}

}

MyTaskTwo.java

public class MyTaskTwo implements Tasklet {

public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {

System.out.println("MyTaskTwo start..");

// ... your code

System.out.println("MyTaskTwo done..");

return RepeatStatus.FINISHED;

}

}

创建批处理作业

现在创建spring批处理作业并在其中配置步骤。我正在创建两个批处理作业。

demoJobOne有2个步骤,即stepOne和stepTwo。

demoJobTwo单步,即stepOne。

BatchConfig.java

import org.springframework.batch.core.Job;

import org.springframework.batch.core.Step;

import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;

import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;

import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import com.howtodoinjava.demo.tasks.MyTaskOne;

import com.howtodoinjava.demo.tasks.MyTaskTwo;

@Configuration

@EnableBatchProcessing

public class BatchConfig {

@Autowired

private JobBuilderFactory jobs;

@Autowired

private StepBuilderFactory steps;

@Bean

public Step stepOne(){

return steps.get("stepOne")

.tasklet(new MyTaskOne())

.build();

}

@Bean

public Step stepTwo(){

return steps.get("stepTwo")

.tasklet(new MyTaskTwo())

.build();

}

@Bean(name="demoJobOne")

public Job demoJobOne(){

return jobs.get("demoJobOne")

.start(stepOne())

.next(stepTwo())

.build();

}

@Bean(name="demoJobTwo")

public Job demoJobTwo(){

return jobs.get("demoJobTwo")

.flow(stepOne())

.build()

.build();

}

}

使用QuartzJobBean创建Quartz作业运行器

现在我们需要创建标准QuartzJobBean实例,我们将使用它来执行批处理作业。

CustomQuartzJob.java:

import org.quartz.JobExecutionContext;

import org.quartz.JobExecutionException;

import org.springframework.batch.core.Job;

import org.springframework.batch.core.JobParameters;

import org.springframework.batch.core.JobParametersBuilder;

import org.springframework.batch.core.configuration.JobLocator;

import org.springframework.batch.core.launch.JobLauncher;

import org.springframework.scheduling.quartz.QuartzJobBean;

public class CustomQuartzJob extends QuartzJobBean {

private String jobName;

private JobLauncher jobLauncher;

private JobLocator jobLocator;

public String getJobName() {

return jobName;

}

public void setJobName(String jobName) {

this.jobName = jobName;

}

public JobLauncher getJobLauncher() {

return jobLauncher;

}

public void setJobLauncher(JobLauncher jobLauncher) {

this.jobLauncher = jobLauncher;

}

public JobLocator getJobLocator() {

return jobLocator;

}

public void setJobLocator(JobLocator jobLocator) {

this.jobLocator = jobLocator;

}

@Override

protected void executeInternal(JobExecutionContext context) throws JobExecutionException

{

try

{

Job job = jobLocator.getJob(jobName);

JobParameters params = new JobParametersBuilder()

.addString("JobID", String.valueOf(System.currentTimeMillis()))

.toJobParameters();

jobLauncher.run(job, params);

}

catch (Exception e)

{

e.printStackTrace();

}

}

}

在SchedulerFactoryBean中配置石英作业详细信息和触发器

现在是时候配置create quartz JobDetail并将triggers它们注册到spring的上下文中。

JobDetail实例包含有关QuartzJobBean注入的信息和信息JobDataMap。

Trigger 还会创建实例以配置批处理作业执行时间和频率。

最后,添加SchedulerFactoryBean配置quartz的作业详细信息和触发器,并将其生命周期作为Spring应用程序上下文的一部分进行管理。它会在初始化时自动启动调度程序,并在销毁时将其关闭。

QuartzConfig.java

import java.io.IOException;

import java.util.Properties;

import org.quartz.JobBuilder;

import org.quartz.JobDataMap;

import org.quartz.JobDetail;

import org.quartz.SimpleScheduleBuilder;

import org.quartz.Trigger;

import org.quartz.TriggerBuilder;

import org.springframework.batch.core.configuration.JobLocator;

import org.springframework.batch.core.configuration.JobRegistry;

import org.springframework.batch.core.configuration.support.JobRegistryBeanPostProcessor;

import org.springframework.batch.core.launch.JobLauncher;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.config.PropertiesFactoryBean;

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 com.howtodoinjava.demo.jobs.CustomQuartzJob;

@Configuration

public class QuartzConfig

{

@Autowired

private JobLauncher jobLauncher;

@Autowired

private JobLocator jobLocator;

@Bean

public JobRegistryBeanPostProcessor jobRegistryBeanPostProcessor(JobRegistry jobRegistry) {

JobRegistryBeanPostProcessor jobRegistryBeanPostProcessor = new JobRegistryBeanPostProcessor();

jobRegistryBeanPostProcessor.setJobRegistry(jobRegistry);

return jobRegistryBeanPostProcessor;

}

@Bean

public JobDetail jobOneDetail() {

//Set Job data map

JobDataMap jobDataMap = new JobDataMap();

jobDataMap.put("jobName", "demoJobOne");

jobDataMap.put("jobLauncher", jobLauncher);

jobDataMap.put("jobLocator", jobLocator);

return JobBuilder.newJob(CustomQuartzJob.class)

.withIdentity("demoJobOne")

.setJobData(jobDataMap)

.storeDurably()

.build();

}

@Bean

public JobDetail jobTwoDetail() {

//Set Job data map

JobDataMap jobDataMap = new JobDataMap();

jobDataMap.put("jobName", "demoJobTwo");

jobDataMap.put("jobLauncher", jobLauncher);

jobDataMap.put("jobLocator", jobLocator);

return JobBuilder.newJob(CustomQuartzJob.class)

.withIdentity("demoJobTwo")

.setJobData(jobDataMap)

.storeDurably()

.build();

}

@Bean

public Trigger jobOneTrigger()

{

SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder

.simpleSchedule()

.withIntervalInSeconds(10)

.repeatForever();

return TriggerBuilder

.newTrigger()

.forJob(jobOneDetail())

.withIdentity("jobOneTrigger")

.withSchedule(scheduleBuilder)

.build();

}

@Bean

public Trigger jobTwoTrigger()

{

SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder

.simpleSchedule()

.withIntervalInSeconds(20)

.repeatForever();

return TriggerBuilder

.newTrigger()

.forJob(jobTwoDetail())

.withIdentity("jobTwoTrigger")

.withSchedule(scheduleBuilder)

.build();

}

@Bean

public SchedulerFactoryBean schedulerFactoryBean() throws IOException

{

SchedulerFactoryBean scheduler = new SchedulerFactoryBean();

scheduler.setTriggers(jobOneTrigger(), jobTwoTrigger());

scheduler.setQuartzProperties(quartzProperties());

scheduler.setJobDetails(jobOneDetail(), jobTwoDetail());

return scheduler;

}

@Bean

public Properties quartzProperties() throws IOException

{

PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();

propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));

propertiesFactoryBean.afterPropertiesSet();

return propertiesFactoryBean.getObject();

}

}

使用属性文件自定义quartz

在quartz中,您可以从简单的属性文件中控制很多东西。例如

quartz.properties

#scheduler name will be "MyScheduler"

org.quartz.scheduler.instanceName = MyScheduler

#maximum of 3 jobs can be run simultaneously

org.quartz.threadPool.threadCount = 3

#All of Quartz data is held in memory (rather than in a database).

org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore

演示

在运行应用程序之前,请确保已在application.properties文件中禁用了批处理作业自动启动功能。

application.properties

#Disable batch job's auto start

spring.batch.job.enabled=false

#enable h2 databse console

spring.h2.console.enabled=true

现在将应用程序作为Spring批处理应用程序运行并检查日志。

App.java

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class App

{

public static void main(String[] args)

{

SpringApplication.run(App.class, args);

}

}

. ____ _ __ _ _

/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \

( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \

\\/ ___)| |_)| | | | | || (_| | ) ) ) )

' |____| .__|_| |_|_| |_\__, | / / / /

=========|_|==============|___/=/_/_/_/

:: Spring Boot :: (v2.0.3.RELEASE)

2018-07-05 10:50:53 INFO - Starting App on FFC15B4E9C5AA with PID 9740 (C:\Users\zkpkhua\DigitalDashboard_Integrated\App\target\classes started by zkpkhua in C:\Users\zkpkhua\DigitalDashboard_Integrated\App)

2018-07-05 10:50:53 INFO - No active profile set, falling back to default profiles: default

2018-07-05 10:50:53 INFO - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@78b1cc93: startup date [Thu Jul 05 10:50:53 IST 2018]; root of context hierarchy

2018-07-05 10:50:54 INFO - Bean 'org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Hikari' of type [org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Hikari] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

2018-07-05 10:50:54 INFO - Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$169797f6] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

2018-07-05 10:50:54 INFO - Bean 'org.springframework.boot.context.properties.ConversionServiceDeducer$Factory' of type [org.springframework.boot.context.properties.ConversionServiceDeducer$Factory] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

2018-07-05 10:50:54 INFO - Bean 'spring.datasource-org.springframework.boot.autoconfigure.jdbc.DataSourceProperties' of type [org.springframework.boot.autoconfigure.jdbc.DataSourceProperties] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

2018-07-05 10:50:54 INFO - Bean 'dataSource' of type [com.zaxxer.hikari.HikariDataSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

2018-07-05 10:50:54 INFO - Bean 'org.springframework.boot.autoconfigure.jdbc.DataSourceInitializerInvoker' of type [org.springframework.boot.autoconfigure.jdbc.DataSourceInitializerInvoker] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

2018-07-05 10:50:54 INFO - Bean 'org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration' of type [org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$$EnhancerBySpringCGLIB$$165a725c] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

2018-07-05 10:50:54 INFO - Bean 'jobLauncher' of type [com.sun.proxy.$Proxy41] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

2018-07-05 10:50:54 INFO - Bean 'jobRegistry' of type [com.sun.proxy.$Proxy43] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

2018-07-05 10:50:54 INFO - Bean 'quartzConfig' of type [com.howtodoinjava.demo.config.QuartzConfig$$EnhancerBySpringCGLIB$$7dc0f057] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

2018-07-05 10:50:55 INFO - HikariPool-1 - Starting...

2018-07-05 10:50:55 INFO - HikariPool-1 - Start completed.

2018-07-05 10:50:55 INFO - No database type set, using meta data indicating: H2

2018-07-05 10:50:55 INFO - No TaskExecutor has been set, defaulting to synchronous executor.

2018-07-05 10:50:56 INFO - Executing SQL script from class path resource [org/quartz/impl/jdbcjobstore/tables_h2.sql]

2018-07-05 10:50:56 INFO - Executed SQL script from class path resource [org/quartz/impl/jdbcjobstore/tables_h2.sql] in 69 ms.

2018-07-05 10:50:56 INFO - Using default implementation for ThreadExecutor

2018-07-05 10:50:56 INFO - Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl

2018-07-05 10:50:56 INFO - Quartz Scheduler v.2.3.0 created.

2018-07-05 10:50:56 INFO - RAMJobStore initialized.

2018-07-05 10:50:56 INFO - Scheduler meta-data: Quartz Scheduler (v2.3.0) 'schedulerFactoryBean' with instanceId 'NON_CLUSTERED'

Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally.

NOT STARTED.

Currently in standby mode.

Number of jobs executed: 0

Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with 3 threads.

Using job-store 'org.quartz.simpl.RAMJobStore' - which does not support persistence. and is not clustered.

2018-07-05 10:50:56 INFO - Quartz scheduler 'schedulerFactoryBean' initialized from an externally provided properties instance.

2018-07-05 10:50:56 INFO - Quartz scheduler version: 2.3.0

2018-07-05 10:50:56 INFO - JobFactory set to: org.springframework.scheduling.quartz.AdaptableJobFactory@1e7f2e0f

2018-07-05 10:50:56 INFO - Executing SQL script from class path resource [org/springframework/batch/core/schema-h2.sql]

2018-07-05 10:50:56 INFO - Executed SQL script from class path resource [org/springframework/batch/core/schema-h2.sql] in 30 ms.

2018-07-05 10:50:57 INFO - Registering beans for JMX exposure on startup

2018-07-05 10:50:57 INFO - Bean with name 'dataSource' has been autodetected for JMX exposure

2018-07-05 10:50:57 INFO - Located MBean 'dataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=dataSource,type=HikariDataSource]

2018-07-05 10:50:57 INFO - Starting beans in phase 2147483647

2018-07-05 10:50:57 INFO - Starting Quartz Scheduler now

2018-07-05 10:50:57 INFO - Scheduler schedulerFactoryBean_$_NON_CLUSTERED started.

2018-07-05 10:50:57 INFO - Started App in 4.164 seconds (JVM running for 4.941)

2018-07-05 10:50:57 INFO - Job: [SimpleJob: [name=demoJobOne]] launched with the following parameters: [{JobID=1530768057055}]

2018-07-05 10:50:57 INFO - Job: [FlowJob: [name=demoJobTwo]] launched with the following parameters: [{JobID=1530768057057}]

2018-07-05 10:50:57 INFO - Executing step: [stepOne]

MyTaskOne start..

MyTaskOne done..

2018-07-05 10:50:57 INFO - Executing step: [stepTwo]

MyTaskTwo start..

MyTaskTwo done..

2018-07-05 10:50:57 INFO - Executing step: [stepOne]

2018-07-05 10:50:57 INFO - Job: [SimpleJob: [name=demoJobOne]] completed with the following parameters: [{JobID=1530768057055}] and the following status: [COMPLETED]

MyTaskOne start..

MyTaskOne done..

2018-07-05 10:50:57 INFO - Job: [FlowJob: [name=demoJobTwo]] completed with the following parameters: [{JobID=1530768057057}] and the following status: [COMPLETED]

2018-07-05 10:51:05 INFO - Job: [SimpleJob: [name=demoJobOne]] launched with the following parameters: [{JobID=1530768065955}]

2018-07-05 10:51:05 INFO - Executing step: [stepOne]

MyTaskOne start..

MyTaskOne done..

2018-07-05 10:51:05 INFO - Executing step: [stepTwo]

MyTaskTwo start..

MyTaskTwo done..

2018-07-05 10:51:05 INFO - Job: [SimpleJob: [name=demoJobOne]] completed with the following parameters: [{JobID=1530768065955}] and the following status: [COMPLETED]

2018-07-05 10:51:15 INFO - Job: [SimpleJob: [name=demoJobOne]] launched with the following parameters: [{JobID=1530768075955}]

2018-07-05 10:51:15 INFO - Executing step: [stepOne]

MyTaskOne start..

MyTaskOne done..

2018-07-05 10:51:15 INFO - Executing step: [stepTwo]

MyTaskTwo start..

MyTaskTwo done..

2018-07-05 10:51:15 INFO - Job: [SimpleJob: [name=demoJobOne]] completed with the following parameters: [{JobID=1530768075955}] and the following status: [COMPLETED]

2018-07-05 10:51:15 INFO - Job: [FlowJob: [name=demoJobTwo]] launched with the following parameters: [{JobID=1530768075980}]

2018-07-05 10:51:15 INFO - Executing step: [stepOne]

MyTaskOne start..

MyTaskOne done..

2018-07-05 10:51:16 INFO - Job: [FlowJob: [name=demoJobTwo]] completed with the following parameters: [{JobID=1530768075980}] and the following status: [COMPLETED]

显然,两个Spring Boot批处理作业都是根据Quartz触发器中配置的计划执行的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring Boot可以很方便地整合Quartz,只需要在pom.xml中添加相关依赖,然后在配置文件中配置Quartz相关属性即可。 具体步骤如下: 1. 在pom.xml中添加Quartz依赖: ``` <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.3.2</version> </dependency> ``` 2. 在配置文件中配置Quartz相关属性: ``` spring.quartz.job-store-type=jdbc spring.quartz.jdbc.initialize-schema=always spring.quartz.properties.org.quartz.scheduler.instanceName=myScheduler spring.quartz.properties.org.quartz.scheduler.instanceId=AUTO spring.quartz.properties.org.quartz.jobStore.class=org.quartz.impl.jdbcjobstore.JobStoreTX spring.quartz.properties.org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.StdJDBCDelegate spring.quartz.properties.org.quartz.jobStore.dataSource=myDS spring.quartz.properties.org.quartz.jobStore.tablePrefix=QRTZ_ spring.quartz.properties.org.quartz.dataSource.myDS.driverClassName=com.mysql.jdbc.Driver spring.quartz.properties.org.quartz.dataSource.myDS.URL=jdbc:mysql://localhost:3306/quartz?useUnicode=true&characterEncoding=utf-8&useSSL=false spring.quartz.properties.org.quartz.dataSource.myDS.user=root spring.quartz.properties.org.quartz.dataSource.myDS.password=root ``` 3. 创建Job类和Trigger类: ``` @Component public class MyJob implements Job { @Override public void execute(JobExecutionContext context) throws JobExecutionException { System.out.println("Hello, Quartz!"); } } @Configuration public class QuartzConfig { @Bean public JobDetail myJobDetail() { return JobBuilder.newJob(MyJob.class) .withIdentity("myJob") .storeDurably() .build(); } @Bean public Trigger myTrigger() { return TriggerBuilder.newTrigger() .forJob(myJobDetail()) .withIdentity("myTrigger") .withSchedule(CronScheduleBuilder.cronSchedule("/5 * * * * ?")) .build(); } } ``` 4. 在启动类中注入SchedulerFactoryBean并启动Quartz: ``` @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Autowired private SchedulerFactoryBean schedulerFactoryBean; @PostConstruct public void startQuartz() throws SchedulerException { schedulerFactoryBean.getScheduler().scheduleJob(quartzConfig.myJobDetail(), quartzConfig.myTrigger()); } } ``` 这样就完成了Spring Boot整合Quartz配置。在启动应用程序时,Quartz会自动创建表并启动定时任务。 ### 回答2: Spring Boot是基于Spring Framework的快速应用开发框架,而Quartz是一个任务调度框架,可以帮助我们定义和执行各种类型的后台作业。本文将为你介绍如何使用Spring Boot整合Quartz框架。 1. 添加依赖 在Spring Boot中使用Quartz需要添加以下依赖: ``` <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz-jobs</artifactId> <version>2.3.0</version> </dependency> ``` 2. 配置JobQuartz中,Job是需要执行的任务,我们需要定义一个类来实现这个Job。 ``` public class MyJob implements Job { @Override public void execute(JobExecutionContext context) throws JobExecutionException { // 任务逻辑 } } ``` 3. 配置Trigger 在Quartz中,Trigger用于定义任务执行的时间和频率。 ``` public class MyTrigger { public Trigger getTrigger() { return TriggerBuilder.newTrigger() .withIdentity("myTrigger", "group1") .withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?")) .forJob("myJob", "group1") .build(); } } ``` 在上面的代码中,我们使用Cron表达式来定义Job的执行时间。 4. 配置Scheduler 在Quartz中,Scheduler是最核心的部分,它负责管理所有的Job和Trigger,并按照预定的时间执行任务。 ``` @Configuration public class SchedulerConfig { @Autowired private ApplicationContext applicationContext; @Bean public SchedulerFactoryBean schedulerFactoryBean() throws IOException { SchedulerFactoryBean factory = new SchedulerFactoryBean(); factory.setQuartzProperties(quartzProperties()); factory.setJobFactory(springBeanJobFactory()); return factory; } @Bean public Properties quartzProperties() throws IOException { PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean(); propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties")); propertiesFactoryBean.afterPropertiesSet(); return propertiesFactoryBean.getObject(); } @Bean public SpringBeanJobFactory springBeanJobFactory() { AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory(); jobFactory.setApplicationContext(applicationContext); return jobFactory; } @Bean public Scheduler scheduler() throws IOException { return schedulerFactoryBean().getScheduler(); } @Bean public JobDetail myJobDetail() { return JobBuilder.newJob(MyJob.class) .withIdentity("myJob", "group1") .storeDurably() .build(); } @Bean public Trigger myTrigger() { return new MyTrigger().getTrigger(); } @PostConstruct public void init() throws SchedulerException, IOException { scheduler().addJob(myJobDetail(), true); scheduler().scheduleJob(myTrigger()); scheduler().start(); } } ``` 在上面的代码中,我们创建了一个SchedulerFactoryBean用于创建Scheduler实例,并在配置类中创建了多个Bean,包括JobDetail、Trigger和自定义的SpringBeanJobFactory。 最后,在@PostConstruct注解下,我们将Job和Trigger添加到Scheduler实例中,并启动Scheduler开始任务调度。 5. 编写Quartz.properties文件 在resources目录下创建quartz.properties文件,用于配置Quartz的一些属性。 ``` org.quartz.scheduler.instanceName = MyScheduler org.quartz.threadPool.threadCount = 3 org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate org.quartz.jobStore.dataSource = myDS org.quartz.jobStore.tablePrefix = QRTZ_ org.quartz.dataSource.myDS.driver = com.mysql.jdbc.Driver org.quartz.dataSource.myDS.URL = jdbc:mysql://localhost:3306/mydb org.quartz.dataSource.myDS.user = myuser org.quartz.dataSource.myDS.password = mypassword org.quartz.dataSource.myDS.maxConnections = 10 ``` 以上就是使用Spring Boot整合Quartz框架的全部步骤,通过以上步骤,我们可以轻松地创建和调度各种类型的后台任务。 ### 回答3: Spring Boot 是一个基于 Spring 框架的快速开发框架,使得构建Spring应用程序非常容易。Quartz 是一个用于作业调度的开源框架,可以通过定义任务和调度器来实现任务的自动化调度。Spring BootQuartz 框架的整合,则可以帮助开发人员更加便捷地实现任务调度。 Spring Boot整合Quartz的步骤如下: 1.在 pom.xml 中添加 Quartz 的依赖: ```xml <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.3.0</version> </dependency> ``` 2.创建一个 Job 类,在该类中实现具体要执行的任务逻辑,并继承 org.quartz.Job 接口: ```java public class HelloWorldJob implements Job{ public void execute(JobExecutionContext context) throws JobExecutionException { System.out.println("Hello World."); } } ``` 3.在配置文件中添加 quartz 相关的配置,例如在 application.properties 文件中添加如下配置: ``` spring.quartz.job-store-type=jdbc spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=123456 spring.quartz.jdbc.initialize-schema=always ``` 4.创建 SchedulerFactoryBean 类,用于创建调度器,并将 Job 注册到调度器中: ```java @Configuration public class QuartzConfig { @Autowired private DataSource dataSource; @Bean public JobDetail jobDetail() { return JobBuilder.newJob(HelloWorldJob.class) .withIdentity("helloJob") .storeDurably() .build(); } @Bean public Trigger trigger() { SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule() .withIntervalInSeconds(10) .repeatForever(); return TriggerBuilder.newTrigger() .forJob(jobDetail()) .withIdentity("helloTrigger") .withSchedule(scheduleBuilder) .build(); } @Bean public SchedulerFactoryBean schedulerFactory() { SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean(); schedulerFactoryBean.setDataSource(dataSource); schedulerFactoryBean.setJobDetails(jobDetail()); schedulerFactoryBean.setTriggers(trigger()); return schedulerFactoryBean; } } ``` 在 SchedulerFactoryBean 类中,首先创建了一个 JobDetail 类,用于描述 Job 相关的信息。然后,通过调用 TriggerBuilder 类的 newTrigger() 方法创建了一个 trigger,用于描述 Job 调度的策略和时间。最后,通过调用 SchedulerFactoryBean 的 setJobDetails() 方法和 setTriggers() 方法将 Job 和 trigger 注册到调度器中。 5.启动应用程序,任务就会开始按照调度器中定义的策略自动运行。 总的来说,Spring Boot整合Quartz非常容易,只需添加相应的依赖、编写 Job 类和 SchedulerFactoryBean 类,并在配置文件中添加相关的配置即可获得方便的任务调度功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值