027_Quartz定时任务框架

1. Quartz的介绍

027_Quartz定时任务框架

2. Quartz的使用思路 

2.1. job任务: 你要做什么事?

2.2. Trigger触发器: 你什么时候去做?

2.3. Scheduler任务调度: 你什么时候需要去做什么事?

3. Quartz的基本使用方式

3.1. 使用maven构建名叫quartz项目

 027_Quartz定时任务框架

3.2. Quartz坐标 

027_Quartz定时任务框架

3.3. pom.xml 

<project xmlns="http://maven.apache.org/POM/4.0.0"
	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">

	<modelVersion>4.0.0</modelVersion>
	<groupId>com.bjbs</groupId>
	<artifactId>quartz</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<!-- 修改jdk版本 -->
	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<!-- Quartz坐标 -->
		<dependency>
			<groupId>org.quartz-scheduler</groupId>
			<artifactId>quartz</artifactId>
			<version>2.2.1</version>
		</dependency>
	</dependencies>
</project>

3.4. 新建QuartzDemo.java

package com.bjbs.quartz;

import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

/**
 * 定义任务类
 */
public class QuartzDemo implements Job {
	/**
	 * 任务被触发时所执行的方法
	 */
	public void execute(JobExecutionContext context) throws JobExecutionException {
		System.out.println("定时器被触发: " + new Date());
	}
}

3.5. 新建QuartzMain.java

package com.bjbs.quartz;

import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

public class QuartzMain {
	public static void main(String[] args) throws Exception {
		// 1.创建Job对象: 你要做什么事?
		JobDetail job = JobBuilder.newJob(QuartzDemo.class).build();

		// 2. 创建Trigger对象: 在什么时间做?
		Trigger trigger = TriggerBuilder.newTrigger().withSchedule(SimpleScheduleBuilder.repeatSecondlyForever()).build();

		// 3.创建Scheduler对象: 在什么时间做什么事?
		Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
		scheduler.scheduleJob(job, trigger);

		// 启动
		scheduler.start();
	}
}

3.6. 运行项目

027_Quartz定时任务框架

4. SpringBoot整合Quartz定时框架

4.1. 使用maven构建SpringBoot的名叫spring-boot-quartz项目

 027_Quartz定时任务框架

4.2. pom.xml 

<project xmlns="http://maven.apache.org/POM/4.0.0"
	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">

	<modelVersion>4.0.0</modelVersion>
	<groupId>com.bjbs</groupId>
	<artifactId>spring-boot-quartz</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.13.RELEASE</version>
	</parent>

	<!-- 修改jdk版本 -->
	<properties>
		<java.version>1.8</java.version>
		<!-- 指定thymeleaf和thymeleaf-layout-dialect高版本可以防止html标签不规范报错 -->
		<thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
		<thymeleaf-layout-dialect.version>2.0.4</thymeleaf-layout-dialect.version>
	</properties>

	<dependencies>
		<!-- springBoot的启动器 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!-- springBoot thymeleaf的启动器 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>

		<!-- Quartz坐标 -->
		<dependency>
			<groupId>org.quartz-scheduler</groupId>
			<artifactId>quartz</artifactId>
			<version>2.2.1</version>
			<exclusions>
				<exclusion>
					<artifactId>slf4j-api</artifactId>
					<groupId>org.slf4j</groupId>
				</exclusion>
			</exclusions>
		</dependency>
		<!-- 添加Scheduled坐标 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
		</dependency>
		<!-- spring tx 坐标 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
		</dependency>
	</dependencies>
</project>

4.3. 新建QuartzDemo.java定义任务类

package com.bjbs.quartz;

import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

/**
 * 定义任务类
 */
public class QuartzDemo implements Job {
	/**
	 * 任务被触发时所执行的方法
	 */
	public void execute(JobExecutionContext context) throws JobExecutionException {
		System.out.println("定时器被触发: " + new Date());
	}
}

4.4. 新建QuartzConfig.java, Quartz配置类

package com.bjbs.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import com.bjbs.quartz.QuartzDemo;

/**
 * Quartz配置类
 */
@Configuration
public class QuartzConfig {
	/**
	 * 1. 创建Job对象
	 */
	@Bean
	public JobDetailFactoryBean jobDetailFactoryBean() {
		JobDetailFactoryBean factory = new JobDetailFactoryBean();
		// 关联我们自己的Job类
		factory.setJobClass(QuartzDemo.class);
		return factory;
	}

	/**
	 * 2. 创建Trigger对象 简单的Trigger
	 */
	@Bean
	public CronTriggerFactoryBean cronTriggerFactoryBean(JobDetailFactoryBean jobDetailFactoryBean) {
		CronTriggerFactoryBean factory = new CronTriggerFactoryBean();
		factory.setJobDetail(jobDetailFactoryBean.getObject());
		// 设置触发时间
		factory.setCronExpression("0/2 * * * * ?");
		return factory;
	}

	/**
	 * 3. 创建Scheduler对象
	 */
	@Bean
	public SchedulerFactoryBean schedulerFactoryBean(CronTriggerFactoryBean cronTriggerFactoryBean) {
		SchedulerFactoryBean factory = new SchedulerFactoryBean();
		// 关联trigger
		factory.setTriggers(cronTriggerFactoryBean.getObject());
		return factory;
	}
}

4.5. 新建App.java

package com.bjbs;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

/**
 * spring Boot整合Quartz案例
 */
@SpringBootApplication
@EnableScheduling // 在启动类上, 添加开启定时任务的注解
public class App {
	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}
}

4.6. 运行项目

027_Quartz定时任务框架

4.7. 新建UserService.java 

package com.bjbs.service;

import org.springframework.stereotype.Service;

@Service
public class UserService {
	public void addUser() {
		System.out.println("Add User......");
	}
}

4.8. 修改QuartzDemo.java, 调用Service

package com.bjbs.quartz;

import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import com.bjbs.service.UserService;

/**
 * 定义任务类
 */
public class QuartzDemo implements Job {
	@Autowired
	private UserService userService;
	
	/**
	 * 任务被触发时所执行的方法
	 */
	public void execute(JobExecutionContext context) throws JobExecutionException {
		System.out.println("定时器被触发: " + new Date());
		
		userService.addUser();
	}
}

4.9. 运行项目, 直接报空指针异常

027_Quartz定时任务框架

4.10. 空指针是userService为空了, 它需要Spring来实例化, 而我们的QuartzDemo类是交给JobDetailFactoryBean类来实例化, QuartzDemo类不是通过Spring类实例化的, 它内部变量自然也不会通过Spring来实例化, 所以为空了。 

027_Quartz定时任务框架

4.11. Job对象是在AdaptableJobFactory直接new出来的。 

027_Quartz定时任务框架

4.12. 我们要想userService变量不为空, QuartzDemo就需要通过Spring IOC来创建, 一路向上, 我们可以编写一个MyAdaptableJobFactory类, 继承自AdaptableJobFactory, MyAdaptableJobFactory类通过Spring IOC来创建。新建MyAdaptableJobFactory.java 

package com.bjbs.config;

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

@Component("myAdaptableJobFactory")
public class MyAdaptableJobFactory extends AdaptableJobFactory {
	// AutowireCapableBeanFactory 可以将一个对象添加到SpringIOC容器中, 并且完成该对象注入
	@Autowired
	private AutowireCapableBeanFactory autowireCapableBeanFactory;

	/**
	 * 该方法需要将实例化的任务对象手动的添加到springIOC容器中并且完成对象的注入
	 */
	@Override
	protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
		Object job = super.createJobInstance(bundle);
		// 将job对象添加Spring IOC容器中, 并完成注入
		autowireCapableBeanFactory.autowireBean(job);
		return job;
	}
}

4.13. 修改QuartzConfig类, 关联创建Job对象的工厂

027_Quartz定时任务框架

4.14. 运行项目 

027_Quartz定时任务框架

上一篇:HM-SpringCloud微服务系列4.3【SpringAMQP】


下一篇:解决 Swoole 服务报错 Too many open files 文件句柄超出系统限制