springboot集成quartz,实现定时或定期任务

springboot集成quartz
1.首先引入依赖

        
        
            org.springframework.boot
            spring-boot-starter-quartz
        

2.mysql表语句

#1 保存已经触发的触发器状态信息
drop table if exists qrtz_fired_triggers;
#2 存放暂停掉的触发器表表
drop table if exists qrtz_paused_trigger_grps;
#3 调度器状态表
drop table if exists qrtz_scheduler_state;
#4 存储程序的悲观锁的信息(假如使用了悲观锁)
drop table if exists qrtz_locks;
#5 简单的触发器表
drop table if exists qrtz_simple_triggers;
#6 存储两种类型的触发器表
drop table if exists qrtz_simprop_triggers;
#7 定时触发器表
drop table if exists qrtz_cron_triggers;
#8 以blob 类型存储的触发器
drop table if exists qrtz_blob_triggers;
#9 触发器表
drop table if exists qrtz_triggers;
#10 job 详细信息表
drop table if exists qrtz_job_details;
#11 日历信息表
drop table if exists qrtz_calendars;
 
#job 详细信息表
create table qrtz_job_details
  (
    sched_name varchar(120) not null,
    job_name  varchar(200) not null,
    job_group varchar(200) not null,
    description varchar(250) null,
    job_class_name   varchar(250) not null,
    is_durable varchar(1) not null,
    is_nonconcurrent varchar(1) not null,
    is_update_data varchar(1) not null,
    requests_recovery varchar(1) not null,
    job_data blob null,
    primary key (sched_name,job_name,job_group)
);
 
#触发器表
create table qrtz_triggers
  (
    sched_name varchar(120) not null,
    trigger_name varchar(200) not null,
    trigger_group varchar(200) not null,
    job_name  varchar(200) not null,
    job_group varchar(200) not null,
    description varchar(250) null,
    next_fire_time bigint(13) null,
    prev_fire_time bigint(13) null,
    priority integer null,
    trigger_state varchar(16) not null,
    trigger_type varchar(8) not null,
    start_time bigint(13) not null,
    end_time bigint(13) null,
    calendar_name varchar(200) null,
    misfire_instr smallint(2) null,
    job_data blob null,
    primary key (sched_name,trigger_name,trigger_group),
    foreign key (sched_name,job_name,job_group)
        references qrtz_job_details(sched_name,job_name,job_group)
);
 
#简单的触发器表,包括重复次数,间隔,以及已触发的次数
create table qrtz_simple_triggers
  (
    sched_name varchar(120) not null,
    trigger_name varchar(200) not null,
    trigger_group varchar(200) not null,
    repeat_count bigint(7) not null,
    repeat_interval bigint(12) not null,
    times_triggered bigint(10) not null,
    primary key (sched_name,trigger_name,trigger_group),
    foreign key (sched_name,trigger_name,trigger_group)
        references qrtz_triggers(sched_name,trigger_name,trigger_group)
);
 
#定时触发器表,存储 cron trigger,包括 cron 表达式和时区信息
create table qrtz_cron_triggers
  (
    sched_name varchar(120) not null,
    trigger_name varchar(200) not null,
    trigger_group varchar(200) not null,
    cron_expression varchar(200) not null,
    time_zone_id varchar(80),
    primary key (sched_name,trigger_name,trigger_group),
    foreign key (sched_name,trigger_name,trigger_group)
        references qrtz_triggers(sched_name,trigger_name,trigger_group)
);
 
#存储calendarintervaltrigger和dailytimeintervaltrigger两种类型的触发器
create table qrtz_simprop_triggers
  (
    sched_name varchar(120) not null,
    trigger_name varchar(200) not null,
    trigger_group varchar(200) not null,
    str_prop_1 varchar(512) null,
    str_prop_2 varchar(512) null,
    str_prop_3 varchar(512) null,
    int_prop_1 int null,
    int_prop_2 int null,
    long_prop_1 bigint null,
    long_prop_2 bigint null,
    dec_prop_1 numeric(13,4) null,
    dec_prop_2 numeric(13,4) null,
    bool_prop_1 varchar(1) null,
    bool_prop_2 varchar(1) null,
    primary key (sched_name,trigger_name,trigger_group),
    foreign key (sched_name,trigger_name,trigger_group)
    references qrtz_triggers(sched_name,trigger_name,trigger_group)
);
 
#以blob 类型存储的触发器
create table qrtz_blob_triggers
  (
    sched_name varchar(120) not null,
    trigger_name varchar(200) not null,
    trigger_group varchar(200) not null,
    blob_data blob null,
    primary key (sched_name,trigger_name,trigger_group),
    foreign key (sched_name,trigger_name,trigger_group)
        references qrtz_triggers(sched_name,trigger_name,trigger_group)
);
 
#日历信息表, quartz可配置一个日历来指定一个时间范围
create table qrtz_calendars
  (
    sched_name varchar(120) not null,
    calendar_name  varchar(200) not null,
    calendar blob not null,
    primary key (sched_name,calendar_name)
);
 
#存放暂停掉的触发器表表
create table qrtz_paused_trigger_grps
  (
    sched_name varchar(120) not null,
    trigger_group  varchar(200) not null,
    primary key (sched_name,trigger_group)
);
 
# 存储与已触发的 trigger 相关的状态信息,以及相联 job 的执行信息
create table qrtz_fired_triggers
  (
    sched_name varchar(120) not null,
    entry_id varchar(95) not null,
    trigger_name varchar(200) not null,
    trigger_group varchar(200) not null,
    instance_name varchar(200) not null,
    fired_time bigint(13) not null,
    sched_time bigint(13) not null,
    priority integer not null,
    state varchar(16) not null,
    job_name varchar(200) null,
    job_group varchar(200) null,
    is_nonconcurrent varchar(1) null,
    requests_recovery varchar(1) null,
    primary key (sched_name,entry_id)
);
 
 #调度器状态表
create table qrtz_scheduler_state
  (
    sched_name varchar(120) not null,
    instance_name varchar(200) not null,
    last_checkin_time bigint(13) not null,
    checkin_interval bigint(13) not null,
    primary key (sched_name,instance_name)
);
#存储程序的悲观锁的信息(假如使用了悲观锁)
create table qrtz_locks
  (
    sched_name varchar(120) not null,
    lock_name  varchar(40) not null,
    primary key (sched_name,lock_name)
);

3.yml配置文件

  #定时配置
  quartz:
    #相关属性配置
    properties:
      org:
        quartz:
          scheduler:
            instanceName: local-scheduler-svc
            instanceId: AUTO
          jobStore:
            #表示 quartz 中的所有数据,比如作业和触发器的信息都保存在内存中(而不是数据库中)
            class: org.springframework.scheduling.quartz.LocalDataSourceJobStore
            # 驱动配置
            driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelegate
            # 表前缀
            tablePrefix: QRTZ_
            #是否为集群
            isClustered: false
            clusterCheckinInterval: 10000
            useProperties: false
            dataSource: quartzDs
          #线程池配置
          threadPool:
            class: org.quartz.simpl.SimpleThreadPool
            #线程数
            threadCount: 10
            #优先级
            threadPriority: 5
            #线程继承上下文类加载器的初始化线程
            threadsInheritContextClassLoaderOfInitializingThread: true
    #数据库方式
    job-store-type: JDBC
    #初始化表结构
    jdbc:
      initialize-schema: NEVER

4.创建参数实体类

import lombok.Data;
import org.quartz.Job;

import java.util.Date;
import org.quartz.JobDataMap;

@Data
public class JobEntity {

    private Class jobClass;

    private String jobName;

    private String jobGroup;

    private private JobDataMap  params;

    private String cron;

    private String timeZoneId = "Asia/Shanghai";

    private Date triggerTime;
}

5.job方法实现

import com.alibaba.fastjson.JSON;
import com.zjf.demo.entity.JobEntity;
import com.zjf.demo.service.ScheduleService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.TimeZone;

@Service
@Slf4j
public class ScheduleServiceImpl implements ScheduleService {

    @Resource
    private Scheduler scheduler;

    @Override
    public JobEntity cronJob(JobEntity job) {
        //查询是否已有相同任务 jobKey可以唯一确定一个任务
        JobKey jobKey = JobKey.jobKey(job.getJobName(), job.getJobGroup());
        try {
            JobDetail jobDetail = scheduler.getJobDetail(jobKey);
            if (Objects.nonNull(jobDetail)) {
                scheduler.deleteJob(jobKey);
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
        }

        //任务详情
        JobDetail jobDetail = JobBuilder.newJob(job.getJobClass())
               .usingJobData(job.getParams())
                .withIdentity(jobKey) //指定任务
                .build();
        //根据cron,TimeZone时区,指定执行计划
        CronScheduleBuilder builder = CronScheduleBuilder.cronSchedule(job.getCron())
                .inTimeZone(TimeZone.getTimeZone(job.getTimeZoneId()));

        //触发器
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(job.getJobName(), job.getJobGroup()).startNow()
                .withSchedule(builder)
                .build();

        //添加任务
        try {
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (SchedulerException e) {
            System.out.println(e.getMessage());
        }
        return job;
    }

    @Override
    public JobEntity triggerTimeJob(JobEntity job) {
        JobKey jobKey = JobKey.jobKey(job.getJobName(), job.getJobGroup());  //作业名称及其组名
        //判断是否有相同的作业
        try {
            JobDetail jobDetail = scheduler.getJobDetail(jobKey);
            if (jobDetail != null) {
                scheduler.deleteJob(jobKey);
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        //定义作业的详细信息,并设置要执行的作业类名,设置作业名称及其组名
        JobDetail jobDetail = JobBuilder.newJob(job.getJobClass())
                .usingJobData(job.getParams())
                .withIdentity(jobKey)
                .build();
        //简单触发器,着重与时间间隔
        SimpleTrigger trigger = (SimpleTrigger) TriggerBuilder.newTrigger()
                .withIdentity(job.getJobName(), job.getJobGroup())
                .startAt(job.getTriggerTime())
                .build();

        try {
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (SchedulerException e) {
            System.out.println(e.getMessage());
        }

        return job;
    }

    @Override
    public void remove(String jobName, String jobGroup) {
        //获取任务触发器
        TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroup);
        try {
            //停止触发器
            scheduler.pauseTrigger(triggerKey);
            //移除触发器
            scheduler.unscheduleJob(triggerKey);
            //删除任务
            scheduler.deleteJob(JobKey.jobKey(jobName, jobGroup));
        } catch (SchedulerException e) {
            System.out.println(e.getMessage());
        }
    }

    @Override
    public void resume(String jobName, String jobGroup) {
        try {
            //根据jobName,jobGroup获取jobKey 恢复任务
            scheduler.resumeJob(JobKey.jobKey(jobName, jobGroup));
        } catch (SchedulerException e) {
            System.out.println(e.getMessage());
        }
    }

    @Override
    public void pause(String jobName, String jobGroup) {
        try {
            //根据jobName,jobGroup获取jobKey 暂停任务
            scheduler.pauseJob(JobKey.jobKey(jobName, jobGroup));
        } catch (SchedulerException e) {
            System.out.println(e.getMessage());
        }
    }

    @Override
    public void trigger(String jobName, String jobGroup) {
        try {
            //根据jobName,jobGroup获取jobKey 立即执行任务
            scheduler.triggerJob(JobKey.jobKey(jobName, jobGroup));
        } catch (SchedulerException e) {
            System.out.println(e.getMessage());
        }
    }

}

6.Job实现类,在里面调用对应的定时调度方法

import com.alibaba.fastjson.JSON;
import com.zjf.demo.quartz.service.TestJobService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

@Slf4j
@Component
public class TestJob implements Job {
    @Resource
    private TestJobService testJobService;

    @Override
    public void execute(JobExecutionContext job) throws JobExecutionException {
        JobKey jobKey = job.getJobDetail().getKey();
        //工作任务名称
        String jobName = jobKey.getName();
        //工作任务组名称
        String groupName = jobKey.getGroup();
        //任务类名称(带路径)
        String classPathName = job.getJobDetail().getJobClass().getName();
        //任务类名称
        String className = job.getJobDetail().getJobClass().getSimpleName();
        //获取Trigger内容
        TriggerKey triggerKey = job.getTrigger().getKey();
        //触发器名称
        String triggerName = triggerKey.getName();
        //出发组名称(带路径)
        String triggerPathName = job.getTrigger().getClass().getName();
        //触发器类名称
        String triggerClassName = job.getTrigger().getClass().getSimpleName();

        String description = job.getJobDetail().getDescription();
        log.info("这儿是执行定时调度任务的地方");

        Map params = (Map) JSON.parse(description);

        testJobService.test(params);

    }
}

7.业务逻辑

@Service
public class TestJobService {

    public void test(Map params) {
        for (Map.Entry entry : params.entrySet()) {
            System.err.println(entry.getKey() + "........." + entry.getValue());
        }

    }
}

8.调用方法,提供两种

@RestController
@RequestMapping("/job")
public class JobController {

    @Resource
    private ScheduleService scheduleService;

    @GetMapping("/test")
    public void test() {
        JobEntity jobInfo = new JobEntity();
        jobInfo.setJobClass(TestJob.class);
        jobInfo.setJobName("maruko");
        jobInfo.setJobGroup("maruko");
        //每5秒执行一次
        jobInfo.setCron("0/5 * * * * ? ");
        JobDataMap params = new JobDataMap();
        params.put("name", "maruko");
        jobInfo.setParams(params);
        scheduleService.cronJob(jobInfo);
    }

    @GetMapping("/test2")
    public void test2() {
        JobEntity jobInfo = new JobEntity();
        jobInfo.setJobClass(TestJob.class);
        jobInfo.setJobName("maruko2");
        jobInfo.setJobGroup("maruko2");
        Date date = new Date();
        //设置当前时间5s后执行
        date.setTime(date.getTime() + 5000);
        jobInfo.setTriggerTime(date);
        JobDataMap params = new JobDataMap();
        params.put("name", "maruko2");
        jobInfo.setParams(params);
        scheduleService.triggerTimeJob(jobInfo);
    }
}

你可能感兴趣的:(spring,boot,java,spring)