在实际开发过程中难免会设置定时任务,定时任务的调用方法也很多,可以通过中间层调用,也可以通过数据库调用,今天就先介绍下中间层调用的方法吧:
环境:
实现大概:
通过写个监听器开启任务,通过Cron表达式进行任务的设置,具体Cron的写法可以在网上生成:http://cron.qqe2.com/
撸代码——QuartzJob.java
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
/**
* 定时任务的东西
*/
public class QuartzJob implements Job {
public static String personinfo="personinfo";
public static String modelPic="modelPic";
public static String identifyResult="identifyResult";
public static String compareResult="compareResult";
public void execute(JobExecutionContext content) throws JobExecutionException {
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+ "★★★★★★★★★★★");
String jobName = content.getJobDetail().getName();
JobDataMap dataMap = content.getJobDetail().getJobDataMap();
String param = dataMap.getString("param");
System.out.println("传递的参数是="+param +"任务名字是="+jobName);
if ("recoveryAnthService-60".equals(jobName)) {
String aag005 = GgfwOutpatientService.selectFWIDIsValid(personinfo);
if ("0".equals(aag005.trim())) {
System.out.println("==========开始恢复服务"+personinfo);
String recoverAuth = GgfwOutpatientService.recoverAuth(personinfo);
System.out.println("==========已完成恢复服务"+personinfo);
}
String aag005_modelPic = GgfwOutpatientService.selectFWIDIsValid(modelPic);
if ("0".equals(aag005_modelPic.trim())) {
System.out.println("==========开始恢复服务"+modelPic);
String recoverAuth = GgfwOutpatientService.recoverAuth(modelPic);
System.out.println("==========已完成恢复服务"+modelPic);
}
String aag005_identifyResult = GgfwOutpatientService.selectFWIDIsValid(identifyResult);
if ("0".equals(aag005_identifyResult.trim())) {
System.out.println("==========开始恢复服务"+identifyResult);
String recoverAuth = GgfwOutpatientService.recoverAuth(identifyResult);
System.out.println("==========已完成恢复服务"+identifyResult);
}
String aag005_compareResult = GgfwOutpatientService.selectFWIDIsValid(compareResult);
if ("0".equals(aag005_compareResult.trim())) {
System.out.println("==========开始恢复服务"+compareResult);
String recoverAuth = GgfwOutpatientService.recoverAuth(compareResult);
System.out.println("==========已完成恢复服务"+compareResult);
}
}
try {
System.out.println("☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆开始执行定时任务了☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆");
//down.dwjfxxDownSw("CBXX004");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
撸代码——QuartzManager.java
package com.xx.jobs;
import java.util.Date;
import java.util.List;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
public class QuartzManager {
private static SchedulerFactory gSchedulerFactory = new StdSchedulerFactory();
private static String JOB_GROUP_NAME = "EXTJWEB_JOBGROUP_NAME";
private static String TRIGGER_GROUP_NAME = "EXTJWEB_TRIGGERGROUP_NAME";
/**
* 添加一个定时任务,使用默认的任务组名,触发器名,触发器组名
* @param jobName 任务名
* @param cls 任务
* @param time 时间设置
*/
@SuppressWarnings("rawtypes")
public static void addJob(String jobName, Class cls, String time) {
try {
Scheduler sched = gSchedulerFactory.getScheduler();
// 任务名,任务组,任务执行类
JobDetail jobDetail = new JobDetail(jobName, JOB_GROUP_NAME, cls);
//可以传递参数
jobDetail.getJobDataMap().put("param", "paramsOfJobs-recoveryAuthService");
// 触发器
CronTrigger trigger = new CronTrigger(jobName, TRIGGER_GROUP_NAME);
// 触发器名,触发器组
trigger.setCronExpression(time);
// 触发器时间设定
sched.scheduleJob(jobDetail, trigger);
// 启动
if (!sched.isShutdown()) {
sched.start();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 修改一个任务的触发时间(使用默认的任务组名,触发器名,触发器组名)
* @param jobName
* @param time
*/
@SuppressWarnings("rawtypes")
public static void modifyJobTime(String jobName, String time) {
try {
Scheduler sched = gSchedulerFactory.getScheduler();
CronTrigger trigger = (CronTrigger) sched.getTrigger(jobName,TRIGGER_GROUP_NAME);
if (trigger == null) {
return;
}
String oldTime = trigger.getCronExpression();
if (!oldTime.equalsIgnoreCase(time)) {
JobDetail jobDetail = sched.getJobDetail(jobName,JOB_GROUP_NAME);
Class objJobClass = jobDetail.getJobClass();
removeJob(jobName);
addJob(jobName, objJobClass, time);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 移除一个任务(使用默认的任务组名,触发器名,触发器组名)
* @param jobName
*/
public static void removeJob(String jobName) {
try {
Scheduler sched = gSchedulerFactory.getScheduler();
sched.pauseTrigger(jobName, TRIGGER_GROUP_NAME);// 停止触发器
sched.unscheduleJob(jobName, TRIGGER_GROUP_NAME);// 移除触发器
sched.deleteJob(jobName, JOB_GROUP_NAME);// 删除任务
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 启动所有定时任务
*/
public static void startJobs() {
try {
Scheduler sched = gSchedulerFactory.getScheduler();
sched.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 关闭所有定时任务
*/
public static void shutdownJobs() {
try {
Scheduler sched = gSchedulerFactory.getScheduler();
if (!sched.isShutdown()) {
sched.shutdown();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void getAllJobs(){
//loop all group
try {
Scheduler scheduler = gSchedulerFactory.getScheduler();
for (String groupName : scheduler.getJobGroupNames()) {
//loop all jobs by groupname
try {
for (String jobName : scheduler.getJobNames(groupName)) {
//get job's trigger
Trigger[] triggers = scheduler.getTriggersOfJob(jobName,groupName);
Date nextFireTime = triggers[0].getNextFireTime();
System.out.println("[jobName] : " + jobName + " [groupName] : "
+ groupName + " - " + nextFireTime);
}
} catch (SchedulerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (SchedulerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
撸代码——QuartzManager.java
package com.xx.jobs;
import java.text.SimpleDateFormat;
import java.util.Date;
public class QuartzTest {
public static void main(String[] args) {
try {
String job_name = "动态任务调度2";
// System.out.println("【任务启动】开始(每10秒输出一次)...");
// QuartzManager.addJob(job_name, QuartzJob.class, "0/10 * * * * ?");
System.out.println("【任务启动】开始(每1分钟输出一次)...");
QuartzManager.addJob(job_name, QuartzJob.class, "0 0/1 * * * ? ");
// QuartzManager.getAllJobs();
// QuartzManager.getAllJobs();
// Thread.sleep(5000);
// System.out.println("【修改时间】开始(每2秒输出一次)...");
// QuartzManager.modifyJobTime(job_name, "10/2 * * * * ?");
// Thread.sleep(6000);
// System.out.println("【移除定时】开始...");
// QuartzManager.removeJob(job_name);
// System.out.println("【移除定时】成功");
// System.out.println("【再次添加定时任务】开始(每10秒输出一次)...");
// QuartzManager.addJob(job_name, QuartzJob.class, "*/10 * * * * ?");
// Thread.sleep(60000);
// System.out.println("【移除定时】开始...");
// QuartzManager.removeJob(job_name);
// System.out.println("【移除定时】成功");
} catch (Exception e) {
e.printStackTrace();
}
}
public static String formatDateByPattern(Date date,String dateFormat){
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
String formatTimeStr = null;
if (date != null) {
formatTimeStr = sdf.format(date);
}
return formatTimeStr;
}
public static String getCron(java.util.Date date){
String dateFormat="ss mm HH dd MM ? yyyy";
return formatDateByPattern(date, dateFormat);
}
}
撸代码——ServiceListen.java
package com.ylzinfo.jobs;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class ServiceListen implements ServletContextListener{
@Override
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
String job_name = "recoveryAnthService-10";
String job_name10 = "recoveryAnthService-60";
System.out.println("恢复服务**recoveryAnthService===0/10 * * * * ?======");
System.out.println("【任务启动】开始(每10秒钟输出一次)...");
QuartzManager.addJob(job_name, QuartzJob.class, "0/10 * * * * ?");
System.out.println("【任务启动】开始(每1分钟输出一次)...");
QuartzManager.addJob(job_name10, QuartzJob.class, "0 0/1 * * * ? ");
}
}
web.xml中的配置:
<listener>
<listener-class>
com.xx.jobs.ServiceListen
</listener-class>
</listener>