pom.xml
<?xml version="1.0" encoding="UTF-8"?> <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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.1.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <groupId>com.wpx</groupId> <artifactId>springboot-Scheduling</artifactId> <version>0.0.1-SNAPSHOT</version> <name>springboot-Scheduling</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.1</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-quartz --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <!-- 修改后立即生效,热部署 --> <dependency> <groupId>org.springframework</groupId> <artifactId>springloaded</artifactId> <version>1.2.8.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
application.yml
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost/quartz?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai username: root password: root quartz: job-store-type: jdbc jdbc: initialize-schema: always mybatis: configuration: map-underscore-to-camel-case: true #spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver #spring.datasource.url=jdbc:mysql:///myblog?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai #spring.datasource.username=root #spring.datasource.password=root
QuartzConfig.java
package com.wpx.quartz.config; import org.quartz.CronScheduleBuilder; import org.quartz.JobBuilder; import org.quartz.JobDetail; import org.quartz.JobKey; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.SimpleScheduleBuilder; import org.quartz.Trigger; import org.quartz.TriggerBuilder; import org.quartz.TriggerKey; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.quartz.SchedulerFactoryBean; import com.wpx.quartz.job.HelloJob; import com.wpx.quartz.job.HelloJob2; @Configuration public class QuartzConfig{ @Autowired private SchedulerFactoryBean SchedulerFactoryBean; @Bean public Scheduler scheduler() throws SchedulerException { Scheduler scheduler = SchedulerFactoryBean.getScheduler(); JobDetail jobDetail = JobBuilder.newJob(HelloJob.class) .withIdentity("job1", "group1") //参数1:任务名称(唯一) 参数2:分配任务组名 .withDescription("我的任务1") .build(); Trigger trigger = TriggerBuilder.newTrigger() .withIdentity("trigger1", "group1") .startNow() //开始的时间 .withSchedule(CronScheduleBuilder.cronSchedule("2/5 * * * * ?")) .build(); JobDetail jobDetail2 = JobBuilder.newJob(HelloJob2.class) .withIdentity("job2", "group1") //参数1:任务名称(唯一) 参数2:分配任务组名 .withDescription("我的任务2") .build(); Trigger trigger2 = TriggerBuilder.newTrigger() .withIdentity("trigger2", "group1") .startNow() //开始的时间 .withSchedule(SimpleScheduleBuilder.repeatSecondlyForever(10)) .build(); scheduler.scheduleJob(jobDetail, trigger); scheduler.scheduleJob(jobDetail2, trigger2); System.out.println(scheduler.getTrigger(TriggerKey.triggerKey("trigger2", "group1"))); return scheduler; } }
JobInfo.java
package com.wpx.quartz.entity; import java.text.SimpleDateFormat; import java.util.Date; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; @Data public class JobInfo { private String jobGroup; private String jobName; private String triggerGroup; private String triggerName; private String description; private String jobClassName; private String triggerState; private String triggerType; private String startTime; private String endTime; private String cronExpressionAndRepeatInterval; private String repeatCount; private String timesTriggered; private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public String getStartTime() { System.out.println(startTime); return sdf.format(new Date(Long.parseLong(startTime))); } public String getEndTime() { if("0".equals(endTime))return "未设定"; return sdf.format(new Date(Long.parseLong(endTime))); } public String getRepeatCount() { if("-1".equals(repeatCount))return "未设定"; return repeatCount; } public String getCronExpressionAndRepeatInterval() { if(cronExpressionAndRepeatInterval != null && cronExpressionAndRepeatInterval.matches("\d+")) { return cronExpressionAndRepeatInterval+"ms"; } return cronExpressionAndRepeatInterval; } }
ResultWrap.java
package com.wpx.quartz.entity; import java.text.SimpleDateFormat; import java.util.Date; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; @Data public class JobInfo { private String jobGroup; private String jobName; private String triggerGroup; private String triggerName; private String description; private String jobClassName; private String triggerState; private String triggerType; private String startTime; private String endTime; private String cronExpressionAndRepeatInterval; private String repeatCount; private String timesTriggered; private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public String getStartTime() { System.out.println(startTime); return sdf.format(new Date(Long.parseLong(startTime))); } public String getEndTime() { if("0".equals(endTime))return "未设定"; return sdf.format(new Date(Long.parseLong(endTime))); } public String getRepeatCount() { if("-1".equals(repeatCount))return "未设定"; return repeatCount; } public String getCronExpressionAndRepeatInterval() { if(cronExpressionAndRepeatInterval != null && cronExpressionAndRepeatInterval.matches("\d+")) { return cronExpressionAndRepeatInterval+"ms"; } return cronExpressionAndRepeatInterval; } }
HelloJob.java
package com.wpx.quartz.job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.quartz.QuartzJobBean; import com.wpx.quartz.server.HelloService; public class HelloJob extends QuartzJobBean{ @Autowired private HelloService helloService; @Override protected void executeInternal(JobExecutionContext context) throws JobExecutionException { helloService.sayHello(context); } }
HelloJob2.java
package com.wpx.quartz.job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.quartz.QuartzJobBean; import com.wpx.quartz.server.HelloService; public class HelloJob2 extends QuartzJobBean{ @Autowired private HelloService helloService; @Override protected void executeInternal(JobExecutionContext context) throws JobExecutionException { helloService.sayHello(context); } }
quartzMapping.java
package com.wpx.quartz.mapper; import java.util.List; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; import com.wpx.quartz.entity.JobInfo; @Mapper public interface quartzMapping { @Select("SELECT " + "qt.JOB_GROUP, " + "qt.JOB_NAME, " + "qjd.DESCRIPTION, " + "qjd.JOB_CLASS_NAME, " + "qt.TRIGGER_STATE, " + "qt.TRIGGER_TYPE, " + "qt.START_TIME, " + "qt.END_TIME, " + "qct.CRON_EXPRESSION cronExpressionAndRepeatInterval, " + "'-' REPEAT_COUNT, " + "'-' TIMES_TRIGGERED " + "FROM qrtz_triggers qt " + "JOIN qrtz_job_details qjd ON qt.JOB_GROUP=qjd.JOB_GROUP AND qt.JOB_NAME=qjd.JOB_NAME " + "JOIN qrtz_cron_triggers qct ON qt.TRIGGER_GROUP=qct.TRIGGER_GROUP AND qt.TRIGGER_NAME=qct.TRIGGER_NAME " + "UNION " + "SELECT " + "qt.JOB_GROUP, " + "qt.JOB_NAME, " + "qjd.DESCRIPTION, " + "qjd.JOB_CLASS_NAME, " + "qt.TRIGGER_STATE, " + "qt.TRIGGER_TYPE, " + "qt.START_TIME, " + "qt.END_TIME, " + "qst.REPEAT_INTERVAL cronExpressionAndRepeatInterval, " + "qst.REPEAT_COUNT, " + "qst.TIMES_TRIGGERED " + " FROM qrtz_triggers qt " + "JOIN qrtz_job_details qjd ON qt.JOB_GROUP=qjd.JOB_GROUP AND qt.JOB_NAME=qjd.JOB_NAME " + "JOIN qrtz_simple_triggers qst ON qt.TRIGGER_GROUP=qst.TRIGGER_GROUP AND qt.TRIGGER_NAME=qst.TRIGGER_NAME") public List<JobInfo> findJobs(); }
HelloService.java
package com.wpx.quartz.server; import java.util.Date; import org.quartz.JobExecutionContext; import org.springframework.stereotype.Service; @Service public class HelloService { public void sayHello(JobExecutionContext context) { System.out.println("hello:"+new Date()+" is "+context.getTrigger().getKey().getName()); } }
QuartzService.java
package com.wpx.quartz.server; import java.util.LinkedList; import java.util.List; import org.quartz.CronScheduleBuilder; import org.quartz.Job; import org.quartz.JobBuilder; import org.quartz.JobDetail; import org.quartz.JobExecutionContext; import org.quartz.JobKey; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.Trigger; import org.quartz.TriggerBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.wpx.quartz.entity.JobInfo; import com.wpx.quartz.entity.ResultWrap; import com.wpx.quartz.job.HelloJob2; import com.wpx.quartz.mapper.quartzMapping; @Service public class QuartzService { @Autowired private Scheduler scheduler; @Autowired quartzMapping quartzMapping; public List<JobInfo> getJobs() throws SchedulerException{ return quartzMapping.findJobs(); } public ResultWrap<Void> addJob(JobInfo info) { try { JobDetail jobDetail = JobBuilder.newJob((Class<? extends Job>)Class.forName(info.getJobClassName())) .withIdentity(info.getJobName(), info.getJobGroup()) .build(); // Trigger trigger = TriggerBuilder.newTrigger() // .withIdentity(info.getTriggerName(), info.getTriggerGroup()) // .startAt() // .withSchedule(CronScheduleBuilder.cronSchedule("0/3 * * * * ?")) // .build(); // // scheduler.scheduleJob(jobDetail, trigger); } catch (Exception e) { e.printStackTrace(); return new ResultWrap<Void>(0, "操作失败"); } return new ResultWrap<Void>(1,"操作成功"); } public ResultWrap<Void> deleteJob(String jobName, String jobGroupName) { try { scheduler.deleteJob(JobKey.jobKey(jobName, jobGroupName)); } catch (SchedulerException e) { e.printStackTrace(); return new ResultWrap<Void>(0, "操作失败"); } return new ResultWrap<Void>(1,"操作成功"); } public ResultWrap<Void> pauseJob(String jobName, String jobGroupName) { try { scheduler.pauseJob(JobKey.jobKey(jobName, jobGroupName)); } catch (SchedulerException e) { e.printStackTrace(); return new ResultWrap<Void>(0, "操作失败"); } return new ResultWrap<Void>(1,"操作成功"); } public ResultWrap<Void> resumeJob(String jobName, String jobGroupName) { try { scheduler.resumeJob(JobKey.jobKey(jobName, jobGroupName)); } catch (SchedulerException e) { e.printStackTrace(); return new ResultWrap<Void>(0, "操作失败"); } return new ResultWrap<Void>(1,"操作成功"); } }
SpringApplication.java
package com.wpx.quartz; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringbootSchedulingApplication { public static void main(String[] args) { SpringApplication.run(SpringbootSchedulingApplication.class, args); } }
quratzController.java
package com.wpx.quartz.controller; import java.util.List; import java.util.Set; import org.quartz.CronScheduleBuilder; import org.quartz.JobBuilder; import org.quartz.JobDetail; import org.quartz.JobKey; import org.quartz.Scheduler; import org.quartz.Trigger; import org.quartz.TriggerBuilder; import org.quartz.impl.matchers.GroupMatcher; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import com.wpx.quartz.entity.JobInfo; import com.wpx.quartz.entity.ResultWrap; import com.wpx.quartz.job.HelloJob2; import com.wpx.quartz.server.QuartzService; @RestController public class quartzController { @Autowired private Scheduler scheduler; @Autowired QuartzService quartzService; @GetMapping("/getjob") public List<JobInfo> getJob() throws Exception { return quartzService.getJobs(); } @GetMapping("/addjob") public Object addJob() throws Exception { return "ok"; } @GetMapping("/deljob") public ResultWrap<Void> delJob(JobInfo info) throws Exception { return quartzService.deleteJob(info.getJobName(), info.getJobGroup()); } @GetMapping("/pausejob") public ResultWrap<Void> pauseJob(JobInfo info) throws Exception { return quartzService.pauseJob(info.getJobName(), info.getJobGroup()); } @GetMapping("/resumejob") public ResultWrap<Void> resumejob(JobInfo info) throws Exception { return quartzService.resumeJob(info.getJobName(), info.getJobGroup()); } }
git参考: https://gitee.com/weipx/springboot-quartz-demo/tree/master/springboot-quartz