17.08.19 Jfinal+QuartzPlugin实现定时执行任务

本文是用配置文件中配置定时任务

1、所需jar包

quartz

http://www.quartz-scheduler.org/downloads/

2、创建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

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

#开启的任务列表“,”隔开
jobArray = task1,task2
 
#搭客任务定时结束
task1.job=com.libo.controller.wx.JobA
task1.cron=00 00 23 * * ?
task1.desc=任务1
 
#归档登录日志
task2.job=com.libo.controller.wx.JobB
task2.cron=00 00 04 * * ?
task2.desc=任务2

备注:在线cron表达式生成器

http://cron.qqe2.com/

4、创建JobBean.java(任务对象实体bean)

/**
 * 计划任务信息
 */
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();
    }
}

5、创建QuartzPlugin.java(插件类)

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.ext.kit.ResourceKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.IPlugin;
import com.libo.model.JobBean;

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;
    }

}

7、创建定时任务

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

public class JobA implements Job {

    @Override
    public void execute(JobExecutionContext arg0) throws JobExecutionException {
        // TODO Auto-generated method stub
        System.out.println("66666666");
    }

}

8、在configPlugin方法中将插件启动

// 配置定时器
QuartzPlugin quartz = new QuartzPlugin();
me.add(quartz);

参考文章:

http://www.jfinal.com/share/15

你可能感兴趣的:(17.08.19 Jfinal+QuartzPlugin实现定时执行任务)