Quartz是一个完全由java编写的开源作业调度框架,他使用非常简单。本章主要讲解 Quartz在Spring Boot 中的使用。
注意:Quartz不是分布式调度,因此只能部署一个实例
分布式调度框架举例:ElasticJob
一、工程
1.1、pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
1.2、Job
package com.wells.demo.quartz.job;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
/**
* Created by Wells on 2019年01月14日
*/
public class WelcomeJob implements Job {
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println("this is a quartz task");
}
}
1.3、启动Job
package com.wells.demo.quartz;
import com.wells.demo.quartz.job.WelcomeJob;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
@SpringBootApplication
@Configuration
@EnableSwagger2
public class QuartzApplication {
public static void main(String[] args) {
SpringApplication.run(QuartzApplication.class, args);
scheduleWelcomeJob();
}
public static void scheduleWelcomeJob() {
// Grab the Scheduler instance from the Factory
Scheduler scheduler = null;
try {
scheduler = StdSchedulerFactory.getDefaultScheduler();
// 启动
scheduler.start();
// 新建一个 Job WelcomeJob
JobDetail job = JobBuilder.newJob(WelcomeJob.class)
.withIdentity("welcomeJob", "simpleGroup")
.build();
// 触发器 定义多长时间触发 JobDetail
Trigger trigger = org.quartz.TriggerBuilder.newTrigger()
.withIdentity("welcomeJob", "simpleGroup")
.startNow()
.withSchedule(simpleSchedule()
.withIntervalInSeconds(10)
.repeatForever())
.build();
scheduler.scheduleJob(job, trigger);
} catch (SchedulerException se) {
se.printStackTrace();
// 关闭
try {
if (scheduler != null) {
scheduler.shutdown();
}
} catch (SchedulerException e) {
e.printStackTrace();
}
}
}
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.wells.demo.quartz"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot Quartz")
.description("更多Spring Boot相关文章请关注:https://www.yuque.com/wells/micro.service")
.contact(new Contact("wells", "", ""))
.version("2.0")
.build();
}
}