以编码方式应用Spring-quartz调度器

注意,quartz 1.x与quartz 2.x相比发生了较大变化,其中jobDetail等类与旧版本相比使用方法不一样的。

使用spring3.2、quartz 2.17

package com.ja.hch.web.sms;

import java.util.List;

import org.apache.log4j.Logger;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.config.Task;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.ja.hch.service.sms.SmsService;
import com.ja.hch.service.sms.impl.SmsServiceImpl;
import com.sun.org.apache.xalan.internal.xsltc.compiler.sym;

@DisallowConcurrentExecution
public class SmsTempletQuartzJob implements Job {
	private static final Logger LOG = Logger.getLogger(SmsTempletQuartzJob.class);
	
	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		try {
			System.out.println("任务运行...");
			LOG.info("短信模板发短信任务运行...");
			
			String sms = (String) context.getMergedJobDataMap().get("sms");
			List<String> sms2PhoneList = (List<String>) context.getMergedJobDataMap().get("sms2PhoneList");
			System.out.println("任务名称: [" + sms + "]\t" + sms2PhoneList);
			WebApplicationContext wac =(WebApplicationContext) context.getMergedJobDataMap().get("wac");
			// 在这里执行任务...
			SmsService service = (SmsService) wac.getBean("smsServiceImpl");
			service.getSmsContent(sms);
			service.sendSms(sms2PhoneList,sms);
			//Thread.sleep(1000 * 9000);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}


package com.ja.hch.web.sms;

import java.util.List;

import jodd.util.StringUtil;

import org.apache.log4j.Logger;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;

public class SmsTempletQuartzManager {
	private static final Logger LOG = Logger.getLogger(SmsTempletQuartzManager.class);
	private static SchedulerFactory gSchedulerFactory = new StdSchedulerFactory();
	public static final String JOB_NAME = "jobName";
	public static final String JOB_GROUP_NAME = "jobGroupName";
	public static final String TRIGGER_NAME = "triggerName";
	public static final String TRIGGER_GROUP_NAME = "triggerGroupName";

	public static String createCronSchedule(String sendMethod, String sendDate) {
		String time = "";
		if (StringUtil.isBlank(sendMethod) || StringUtil.isBlank(sendDate)) {
			time = "";
		} else if ("everyday".equalsIgnoreCase(sendMethod)) {// 每天执行
			time = "0 0 " + sendDate + " ? * *" ;//每天sendDate点触发;
		}
		return time;
	}

	/**
	 * @Description: 添加一个定时任务,使用默认的任务组名,触发器名,触发器组名
	 * 
	 * @param jobName
	 *            任务名
	 * @param cls
	 *            任务
	 * @param time
	 *            时间设置,参考quartz说明文档
	 * 
	 */
	public static void addJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName, String time, String smsContent, List<String> sms2PhoneList) {
		if(StringUtil.isBlank(time)){
			LOG.error("添加一个短信模板定时任务失败;cron表达式错误");
			return;
		}
		try {
			Scheduler sched = gSchedulerFactory.getScheduler();
			JobDetail jobDetail = JobBuilder.newJob(SmsTempletQuartzJob.class).withIdentity(jobName, jobGroupName).build();
			jobDetail.getJobDataMap().put("sms", smsContent);// 短信内容
			jobDetail.getJobDataMap().put("sms2PhoneList", sms2PhoneList);// 手机号码

			// 表达式调度构建器
			CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(time);
			// 按新的表达式构建一个新的trigger
			CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerName, triggerGroupName).withSchedule(scheduleBuilder).build();
			sched.scheduleJob(jobDetail, trigger);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * @Description: 修改一个任务的触发时间
	 * 
	 * @param triggerName
	 * @param triggerGroupName
	 * @param time
	 */
	public static void modifyJobTime(String triggerName, String triggerGroupName, String time) {
		if(StringUtil.isBlank(time)){
			LOG.error("修改一个短信模板定时任务失败;cron表达式错误");
			return;
		}
		try {
			Scheduler sched = gSchedulerFactory.getScheduler();
			TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
			CronTrigger trigger = (CronTrigger) sched.getTrigger(triggerKey);
			if (trigger == null) {
				return;
			}
			String oldTime = trigger.getCronExpression();
			if (!oldTime.equalsIgnoreCase(time)) { // 修改时间
				// 表达式调度构建器
				CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(time);
				// 按新的cronExpression表达式重新构建trigger
				trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
				// 重启触发器
				sched.rescheduleJob(triggerKey, trigger);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * @Description: 移除一个任务
	 * 
	 * @param jobName
	 * @param jobGroupName
	 * @param triggerName
	 * @param triggerGroupName
	 */
	public static void removeJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName) {
		try {
			Scheduler sched = gSchedulerFactory.getScheduler();
			JobKey jobKey = JobKey.jobKey(jobName, jobGroupName);
			TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
			sched.pauseTrigger(triggerKey);// 停止触发器
			sched.unscheduleJob(triggerKey);// 移除触发器
			sched.deleteJob(jobKey);// 删除任务
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * @Description:启动所有定时任务
	 */
	public static void startJobs() {
		try {
			Scheduler sched = gSchedulerFactory.getScheduler();
			if (!sched.isStarted()) {
				sched.start();
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * @Description:关闭所有定时任务
	 */
	public static void shutdownJobs() {
		try {
			Scheduler sched = gSchedulerFactory.getScheduler();
			if (!sched.isShutdown()) {
				sched.shutdown();
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}


调用方法
String JOB_NAME = SmsTempletQuartzManager.JOB_NAME + "_" + TMP_ID;
				String JOB_GROUP_NAME = SmsTempletQuartzManager.JOB_GROUP_NAME + "_" + TMP_ID;
				String TRIGGER_NAME = SmsTempletQuartzManager.TRIGGER_NAME + "_" + TMP_ID;
				String TRIGGER_GROUP_NAME = SmsTempletQuartzManager.TRIGGER_GROUP_NAME + "_" + TMP_ID;
				SmsTempletQuartzManager.addJob(JOB_NAME, JOB_GROUP_NAME, TRIGGER_NAME, TRIGGER_GROUP_NAME, SmsTempletQuartzManager.createCronSchedule(SEND_METHOD,SEND_DATE), TMP_CONTENT, sms2PhoneList);
				SmsTempletQuartzManager.startJobs();


展开阅读全文

没有更多推荐了,返回首页