第一种实现方式
1.导入包
<dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.3.0</version> </dependency>
2:在myconfig中配置quartz插件:
QuartzPlugin quatrZPlugin = new QuartzPlugin();
me.add(quatrZPlugin);//定时任务插件
3.在根目录下设置配置文件,我设置的目录是src/main/resources
quartz_config.properties
#配置主要调度程序属性
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
4.在src/main/java下面编写代码
所需工具类有三个:FormaterCronExpression.java、QuartZKit.java、QuartzPlugin.java;需要一个实体类:JobBean.java;然后就可以编写任务了,目录结构如下图:
(1),config配置类,
(2),任务实体类,
(3),任务实现类,
(4),工具类,
(5).配置文件。
JobBean.java:
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(); } }
FormaterCronExpression.java:
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 ""; } }
QuartZKit.java:
package com.pointlion.sys.plugin.quartz;
import com.pointlion.sys.plugin.quartz.bean.JobBean;
public class QuartZKit { /*** * 动态添加任务 */ public static void addTask(String taskid , String closeTime){ JobBean job = new JobBean(); job.setJobClass("com.pointlion.sys.plugin.quartz.task.ResetYearHoliday"); job.setCronExpression(FormaterCronExpression.formaterCronExpression(closeTime)); job.setJobGroup("DakeTaskJob"); job.setJobDesc("DakeTaskJob_" + taskid); QuartzPlugin.addJob(job); } }
QuartzPlugin.java:
package com.pointlion.sys.plugin.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.jfinal.kit.PropKit; import com.jfinal.kit.StrKit; import com.jfinal.plugin.IPlugin; import com.pointlion.sys.plugin.quartz.bean.JobBean;
public class QuartzPlugin implements IPlugin{
private List<JobBean> jobs = new ArrayList<JobBean>(); private SchedulerFactory sf; private static Scheduler scheduler; private String jobConfig; private String confConfig; private Map<Object, Object> 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"; } @Override public boolean start() { loadJobsFromProperties(); startJobs(); return true; } /*** * 从配置文件中加载任务 */ private void loadJobsFromProperties() { if (StrKit.isBlank(jobConfig)) { return; } jobProp = PropKit.use(jobConfig).getProperties(); String jobArray = (String) jobProp.get("jobArray"); if (StrKit.isBlank(jobArray)) { return; } String[] jobArrayList = jobArray.split(","); for (String jobName : jobArrayList) { jobs.add(createJobBean(jobName)); } } private void startJobs() { try { if (StrKit.notBlank(confConfig)) { sf = new StdSchedulerFactory(confConfig); } else { sf = new StdSchedulerFactory(); } scheduler = sf.getScheduler(); } catch (SchedulerException e) { e.printStackTrace(); } for (JobBean entry : jobs) { addJob(entry); } try { scheduler.start(); } catch (SchedulerException e) { e.printStackTrace(); } } public static void addJob(JobBean job) { try { TriggerKey triggerKey = TriggerKey.triggerKey(job.getJobDesc(), job.getJobGroup()); CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey); // 不存在,创建一个 if (null == trigger) { @SuppressWarnings("unchecked") Class<Job> j2 = (Class<Job>) 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) { } } private JobBean createJobBean(String key) { JobBean job = new JobBean(); job.setJobClass(jobProp.get(key + ".class").toString()); job.setCronExpression(jobProp.get(key + ".cron").toString()); job.setJobGroup(jobProp.get(key+ ".group").toString()); job.setJobDesc(jobProp.get(key + ".desc").toString()); return job; } @Override public boolean stop() { try { scheduler.shutdown(); } catch (SchedulerException e) { e.printStackTrace(); } return true; }
}
任务示例ResetYearHoliday
package com.pointlion.sys.plugin.quartz.task;
import org.quartz.Job; import org.quartz.JobExecutionContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
import com.jfinal.kit.PropKit; import com.jfinal.plugin.activerecord.Db;
public class ResetYearHoliday implements Job{ private static final Logger logger = LoggerFactory.getLogger(ResetYearHoliday.class); @Override public void execute(JobExecutionContext context) { logger.info("*****************************开始重置所有员工年假******************"); Db.update("update sys_user set year_holiday = '"+PropKit.get("yearHoliday").trim()+"' where type='1'"); logger.info("*****************************完成重置所有员工年假******************"); }
}
第一种定时任务实现代码编写结束,启动项目即可运行。
第二种实现方式
前两步和第一种实现方式一致,第三步中除了 需要配置 quartz_config.properties,配置内容和第一种方式中相同名字的配置文件内容一致;还需要配置 quartz_job.properties,配置内容如下 。
quartz_job.properties
#配置第一个定时任务
#开启的任务列表“,”隔开 实际上为group #jobArray = CrawlDataPolicyTask jobArray =CheckTimeTask #搭客任务定时结束 #[秒] [分] [小时] [日] [月] [周] [年] CheckTimeTask.class=com.pointlion.sys.plugin.quartz.task.CheckTimeTask CheckTimeTask.group=CheckTimeTask CheckTimeTask.cron=0 0 1 * * ? CheckTimeTask.desc=\u6BCF\u5E74\u91CD\u7F6E\u5E74\u5047\u6570\u91CF
#配置第二个定时任务
jobArray =DemoTask DemoTask.class=com.pointlion.sys.plugin.quartz.task.DemoTask DemoTask.group=DemoTask DemoTask.cron=0/10 * * * * ? DemoTask.desc=\u6BCF\u5E74\u91CD\u7F6E\u5E74\u5047\u6570\u91CF
第四步所需要的工具类QuartzPlugin.java和实体类JobBean.java和第一种实现方式中的一致。
第五步,编写定时任务内容,如下:
任务实例:DemoTask:
import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException;
public class DemoTask implements Job {
@Override public void execute(JobExecutionContext arg0) throws JobExecutionException { System.out.println("##########开始定时任务##########"); System.out.println("aaaaaaaaaaaaaa"); System.out.println("##########结束定时任务##########"); } }
第二种定时任务代码编写结束,启动项目即可运行。