jfinal定时调度任务插件QuartzPlugin

pom.xml依赖quartz

<dependency>
    <groupId>org.quartz-schedulergroupId>
    <artifactId>quartzartifactId>
    <version>2.2.1version>
dependency>

quartz_config.properties(quartz配置)

#============================================================================
# 配置主要调度程序属性
#============================================================================
org.quartz.scheduler.instanceName = DefaultQuartzScheduler
org.quartz.scheduler.instanceId = AUTO
org.quartz.scheduler.rmi.export = false
org.quartz.scheduler.rmi.proxy = false
org.quartz.scheduler.wrapJobExecutionInUserTransaction = false

#============================================================================
# 配置线程池  
#============================================================================
org.quartz.threadPool.threadCount = 10
org.quartz.threadPool.threadPriority = 5

#============================================================================
# 配置任务 
#============================================================================
org.quartz.jobStore.misfireThreshold = 60000
org.quartz.scheduler.skipUpdateCheck = true

quartz_job.properties(任务配置,默认的调度任务可以在这里添加)

#开启的任务列表“,”隔开
jobArray = task1,task2

#搭客任务定时结束
task1.job=com.guiyang.education.quartz.Task1
task1.cron=00 00 23 * * ?
task1.desc=任务1

#归档登录日志
task2.job=com.guiyang.education.quartz.Task2
task2.cron=00 00 04 * * ?
task2.desc=任务2

FormaterCronExpression.java(日期转cron定时表达式类)

package com.guiyang.education.quartz;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FormaterCronExpression {
    static String formart = "yyyy-MM-dd HH:mm:ss";

    public static String formaterCronExpression(String date) {
        SimpleDateFormat format = new SimpleDateFormat(formart.substring(0, date.length() - 1));
        SimpleDateFormat format2 = new SimpleDateFormat("yyyy MM dd HH mm ss");
        try {
            Date d = format.parse(date);
            date = format2.format(d);
            String[] dateArry = date.split(" ");
            String exp = dateArry[5] + " " + dateArry[4] + " " + dateArry[3] + " " + dateArry[2] + " " + dateArry[1]
                    + " ? " + dateArry[0];
            return exp;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "";
    }
}

JobBean.java(任务对象实体bean)

package com.guiyang.education.quartz;
/**
 * 计划任务信息
 */
public class JobBean {

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

    /** 任务描述 */
    private String jobDesc;

    /** 任务运行时间表达式 */
    private String cronExpression;

    /** 任务分组 */
    private String jobGroup;

    /** 任务类 */
    private String jobClass;

    public String getJobId() {
        return jobId;
    }

    public void setJobId(String jobId) {
        this.jobId = jobId;
    }

    public String getJobDesc() {
        return jobDesc;
    }

    public void setJobDesc(String jobDesc) {
        this.jobDesc = jobDesc;
    }

    public String getCronExpression() {
        return cronExpression;
    }

    public void setCronExpression(String cronExpression) {
        this.cronExpression = cronExpression;
    }

    public String getJobGroup() {
        return jobGroup;
    }

    public void setJobGroup(String jobGroup) {
        this.jobGroup = jobGroup;
    }

    public String getJobClass() {
        return jobClass;
    }

    public void setJobClass(String jobClass) {
        this.jobClass = jobClass;
    }

    public JobBean(String jobId, String jobDesc, String cronExpression, String jobGroup, String jobClass) {
        this.jobId = jobId;
        this.jobDesc = jobDesc;
        this.cronExpression = cronExpression;
        this.jobGroup = jobGroup;
        this.jobClass = jobClass;
    }

    public JobBean() {
        super();
    }
}

QuartzPlugin.java(插件类)

package com.guiyang.education.quartz;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;

import com.google.common.base.Throwables;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.IPlugin;
import com.kabao.ext.kit.ResourceKit;

public class QuartzPlugin implements IPlugin {
    private List jobs = new ArrayList();
    private SchedulerFactory sf;
    private static Scheduler scheduler;
    private String jobConfig;
    private String confConfig;
    private Map jobProp;

    public QuartzPlugin(String jobConfig, String confConfig) {
        this.jobConfig = jobConfig;
        this.confConfig = confConfig;
    }

    public QuartzPlugin(String jobConfig) {
        this.jobConfig = jobConfig;
        this.confConfig = "/quartz_config.properties";
    }

    public QuartzPlugin() {
        this.jobConfig = "/quartz_job.properties";
        this.confConfig = "/quartz_config.properties";
    }

    public static void addJob(JobBean job) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(job.getJobDesc(), job.getJobGroup());
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            // 不存在,创建一个
            if (null == trigger) {
                Class j2 = (Class) Class.forName(job.getJobClass());
                JobDetail jobDetail = JobBuilder.newJob(j2).withIdentity(job.getJobDesc(), job.getJobGroup()).build();
                jobDetail.getJobDataMap().put("scheduleJob", job);

                // 表达式调度构建器
                CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());

                // 按新的cronExpression表达式构建一个新的trigger
                trigger = TriggerBuilder.newTrigger().withIdentity(job.getJobDesc(), job.getJobGroup())
                        .withSchedule(scheduleBuilder).build();
                try {
                    scheduler.scheduleJob(jobDetail, trigger);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                // Trigger已存在,那么更新相应的定时设置
                // 表达式调度构建器
                CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());

                // 按新的cronExpression表达式重新构建trigger
                trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();

                // 按新的trigger重新设置job执行
                scheduler.rescheduleJob(triggerKey, trigger);
            }
        } catch (Exception e) {
        }
    }

    @Override
    public boolean start() {
        loadJobsFromProperties();
        startJobs();
        return true;
    }

    private void startJobs() {
        try {
            if (StrKit.notBlank(confConfig)) {
                sf = new StdSchedulerFactory(confConfig);
            } else {
                sf = new StdSchedulerFactory();
            }
            scheduler = sf.getScheduler();
        } catch (SchedulerException e) {
            Throwables.propagate(e);
        }
        for (JobBean entry : jobs) {
            addJob(entry);
        }
        try {
            scheduler.start();
        } catch (SchedulerException e) {
            Throwables.propagate(e);
        }
    }

    private void loadJobsFromProperties() {
        if (StrKit.isBlank(jobConfig)) {
            return;
        }
        jobProp = ResourceKit.readProperties(jobConfig);
        String jobArray = jobProp.get("jobArray");
        if (StrKit.isBlank(jobArray)) {
            return;
        }
        String[] jobArrayList = jobArray.split(",");
        for (String jobName : jobArrayList) {
            jobs.add(createJobBean(jobName));
        }
    }

    private JobBean createJobBean(String key) {
        JobBean job = new JobBean();
        job.setJobClass(jobProp.get(key + ".job"));
        job.setCronExpression(jobProp.get(key + ".cron"));
        job.setJobGroup(jobProp.get(key));
        job.setJobDesc(jobProp.get(key + ".desc"));
        return job;
    }

    @Override
    public boolean stop() {
        try {
            scheduler.shutdown();
        } catch (SchedulerException e) {
            Throwables.propagate(e);
        }
        return true;
    }
}

configPlugin方法中将插件启动就可以

@Override
public void configPlugin(Plugins me) {

        // 添加quartz插件
        QuartzPlugin quartzPlugin = new QuartzPlugin();
        me.add(quartzPlugin);
}

Task1.java(任务类)

package com.guiyang.education.quartz;

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

public class Task1 implements Job {

    @Override
    public void execute(JobExecutionContext arg0) throws JobExecutionException {
        //这里写任务逻辑
    }

}

附录:动态添加定时任务

JobBean job = new JobBean();
job.setJobClass("com.momoda.quartz.DakeTaskJob");
job.setCronExpression(FormaterCronExpression.formaterCronExpression(task.getStr("closingTime")));
job.setJobGroup("DakeTaskJob");
job.setJobDesc("DakeTaskJob_" + taskid);
QuartzPlugin.addJob(job);

你可能感兴趣的:(Java)