spring定时任务之整合quartz-jobs执行定时任务

spring定时任务之整合quartz-jobs执行定时任务_第1张图片

通过实现job类可以手动执行自定义的定时任务


实现方式如下:

1、引入jar包:


  org.quartz-scheduler
  quartz
  2.2.3


  org.quartz-scheduler
  quartz-jobs
  2.2.3

2、在配置文件中添加配置
 

3、创建数据库

spring定时任务之整合quartz-jobs执行定时任务_第2张图片

4、定时任务实体类:
 

package com.aisino.zhgl.plan.model;

import java.util.Date;
import java.io.Serializable;
import com.aisino.zhgl.core.model.BaseModel;

/**
 * 定时任务(SysSchedule)实体类
 *
 * @author 
 * @since 
 */
public class SysSchedule extends BaseModel {
    private static final long serialVersionUID = -31279662158620438L;
    /**
    * id
    */

    private String id;
    /**
    * 任务名
    */    

    private String name;
    /**
    * 任务组
    */    
    
    private String tGroup;
    /**
    * 定时规则
    */    
    
    private String expression;
    /**
    * 启用状态
    */    
    
    private String status;
    /**
    * 通知用户
    */    
    
    private String isInfo;
    /**
    * 任务类
    */    
    
    private String classname;
    /**
    * 描述
    */    
    
    private String description;
    /**
    * 创建者
    */    
    
    private String createBy;
    /**
    * 创建时间
    */    
    
    private Date createDate;
    /**
    * 更新者
    */    
    
    private String updateBy;
    /**
    * 更新时间
    */    
    
    private Date updateDate;
    /**
    * 逻辑删除标记(0:显示;1:隐藏)
    */    
    
    private String delFlag;

    @Override
    public String getId() {
        return id;
    }

    @Override
    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getTGroup() {
        return tGroup;
    }

    public void setTGroup(String tGroup) {
        this.tGroup = tGroup;
    }

    public String getExpression() {
        return expression;
    }

    public void setExpression(String expression) {
        this.expression = expression;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getIsInfo() {
        return isInfo;
    }

    public void setIsInfo(String isInfo) {
        this.isInfo = isInfo;
    }

    public String getClassname() {
        return classname;
    }

    public void setClassname(String classname) {
        this.classname = classname;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getCreateBy() {
        return createBy;
    }

    public void setCreateBy(String createBy) {
        this.createBy = createBy;
    }

    public Date getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }

    public String getUpdateBy() {
        return updateBy;
    }

    public void setUpdateBy(String updateBy) {
        this.updateBy = updateBy;
    }

    public Date getUpdateDate() {
        return updateDate;
    }

    public void setUpdateDate(Date updateDate) {
        this.updateDate = updateDate;
    }

    public String getDelFlag() {
        return delFlag;
    }

    public void setDelFlag(String delFlag) {
        this.delFlag = delFlag;
    }

}

5、定时任务工具类----封装了调用方法

 

package com.aisino.zhgl.plan.controller.task;

import com.aisino.zhgl.plan.model.SysSchedule;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.stereotype.Controller;

@Controller
public class QuartzTool {

    private static SchedulerFactory schedulerFactory = new StdSchedulerFactory();
    /**
     *  新增一个时间调度器
     * @param triggerName
     * @param triggerGroupName
     * @param jobClass
     * @param cron
     * @return
     */
    public Boolean addQuartz(String triggerName, String triggerGroupName, Class jobClass , String cron){
        try {
            // 创建一个JobDetail实例
            JobDetail jobDetail = JobBuilder.newJob(jobClass).build();
            // 创建一个CronTrigger,规定Job每隔一秒执行一次
            CronTrigger trigger = TriggerBuilder.newTrigger()
                    // 指定Trigger名称和组名称
                    .startNow().withIdentity(triggerName, triggerGroupName)
                    // 设置cron运行规则,定义每秒执行一次
                    .withSchedule(CronScheduleBuilder.cronSchedule(cron)).build();
            // 得到Scheduler调度器实例
            Scheduler scheduler = null;
            scheduler = new StdSchedulerFactory().getScheduler();
            scheduler.scheduleJob(jobDetail, trigger); // 绑定JobDetail和Trigger
            scheduler.start(); // 开始任务调度
            return true;
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     *  修改一个时间调度器
     * @param triggerName
     * @param triggerGroupName
     * @param cron
     * @return
     */
    public  Boolean modifyQuartz(String triggerName, String triggerGroupName, String cron) {
        try {
            Scheduler scheduler = schedulerFactory.getScheduler();
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            if (trigger == null) {
                return false ;
            }
            String oldTime = trigger.getCronExpression();
            if (!oldTime.equalsIgnoreCase(cron)) {
                // 触发器
                TriggerBuilder triggerBuilder = TriggerBuilder.newTrigger();
                // 触发器名,触发器组
                triggerBuilder.withIdentity(triggerName, triggerGroupName);
                triggerBuilder.startNow();
                // 触发器时间设定
                triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
                // 创建Trigger对象
                trigger = (CronTrigger) triggerBuilder.build();
                // 修改一个任务的触发时间
                scheduler.rescheduleJob(triggerKey, trigger);
            }
            return true ;
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     *  移除一个定时器
     * @param triggerName
     * @param triggerGroupName
     */
    public Boolean removeQuartz(String triggerName, String triggerGroupName) {
        try {
            Scheduler scheduler = schedulerFactory.getScheduler();

            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName,triggerGroupName);
            // 停止触发器
            scheduler.pauseTrigger(triggerKey);
            // 移除触发器
            scheduler.unscheduleJob(triggerKey);
            return  true;
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 恢复任务
     */
    public void restartJob(SysSchedule quartzRequest){
        try {
            Scheduler scheduler = schedulerFactory.getScheduler();
            TriggerKey triggerKey = TriggerKey.triggerKey(quartzRequest.getName(),quartzRequest.getTGroup());
//            scheduler.resumeTrigger(triggerKey);
            // 停止触发器
            scheduler.pauseTrigger(triggerKey);
            // 移除触发器
            scheduler.unscheduleJob(triggerKey);

            addQuartz(quartzRequest.getName(),quartzRequest.getTGroup(),Class.forName(quartzRequest.getClassname()),quartzRequest.getExpression());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 立马执行一次任务
     * @param triggerName 任务名
     * @param triggerGroupName 任务组
     */
    public void startNowJob(String triggerName, String triggerGroupName){
        try {
            Scheduler scheduler = schedulerFactory.getScheduler();
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName,triggerGroupName);
            Trigger trigger = scheduler.getTrigger(triggerKey);
            JobKey jobKey = trigger.getJobKey();
            scheduler.triggerJob(jobKey);
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 暂停任务
     * @param triggerName 任务名
     * @param triggerGroupName 任务组
     */
    public void stopJob(String triggerName, String triggerGroupName){
        try {
            Scheduler scheduler = schedulerFactory.getScheduler();
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName,triggerGroupName);
            // 停止触发器
            scheduler.pauseTrigger(triggerKey);
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     *
     * 启动所有定时任务
     */
    public  Boolean startJobs() {
        try {
            Scheduler scheduler = schedulerFactory.getScheduler();
            scheduler.start();
            return  true;
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 功能:关闭所有定时任务
     */
    public Boolean shutdownJobs() {
        try {
            Scheduler scheduler = schedulerFactory.getScheduler();
            if (!scheduler.isShutdown()) {
                scheduler.shutdown();
            }
            return  true;
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }

}

6、定义类实现Job

package com.aisino.zhgl.plan.controller.task;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.text.SimpleDateFormat;

public abstract class Task implements Job {

    static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");


    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        run();
    }

    public abstract void run();

}
package com.aisino.zhgl.plan.controller.task;

import java.text.SimpleDateFormat;
import java.util.Date;

public class QuartzJob extends Task {

    @Override
    public void run() {
        // 任务逻辑代码
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        System.out.println("=========================================");
        System.out.println("定时任务测试======QuartzJob" + df.format(new Date()));
        System.out.println("=========================================");
        System.out.println();
    }

}

 

以上可以实现手动添加自定义定时任务的基本功能,具体需要根据业务修改

 

 

 

 

你可能感兴趣的:(java,quartz,触发器,spring,cron)