不同框架下使用定时器的总结
作者:vashon
时间:20151226
本篇介绍两套框架下quartz的使用
首先下载quartz-1.6.0.jar架包,并添加到lib目录下。
package com.xxx.xxx.mail.timer; import org.nutz.ioc.loader.annotation.IocBean; import org.quartz.CronTrigger; import org.quartz.JobBuilder; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.SchedulerFactory; import org.quartz.impl.StdSchedulerFactory; /** * 邮件定时器 * @author ywx * */ @IocBean public class MailSchedule { SchedulerFactory sf = null; Scheduler sched = null; JobDetail job = null; /** * 启动定时器 */ public void startSchedule(){ sf = new StdSchedulerFactory(); try { sched=sf.getScheduler(); job=JobBuilder.newJob(MailJob.class).build(); CronTrigger cTrigger=new MailCronTrigger().cronTrigger; sched.scheduleJob(job, cTrigger); sched.start(); } catch (SchedulerException e) { e.printStackTrace(); } } /** * 停止定时器 */ public void shutdownSchedule() { if (null != sched) { try { sched.shutdown(); } catch (SchedulerException e) { e.printStackTrace(); } } } }
package com.xxx.xxx.mail.timer; import java.util.Calendar; import java.util.Date; import org.nutz.ioc.Ioc; import org.nutz.ioc.impl.NutIoc; import org.nutz.ioc.loader.combo.ComboIocLoader; import org.nutz.log.Log; import org.nutz.log.Logs; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import com.xxx.xxx.at.MeetingAt; import com.xxx.util.MailUtils; import com.xxx.util.PropertyUtils; /** * 定时器执行任务内容 * @author ywx * */ public class MailJob implements Job{ Ioc ioc = null; private Log logger = Logs.get(); private MailUtils mailUtils=null; /** * 获取当前日期是星期几 * @param time 当前日期 * @return * @throws Exception */ public static String isFriday(Date time){ Calendar c=Calendar.getInstance(); c.setTime(time); int dayForWeek=0; if(c.get(Calendar.DAY_OF_WEEK)==1){ dayForWeek=7; }else{ dayForWeek=c.get(Calendar.DAY_OF_WEEK)-1; } return String.valueOf(dayForWeek); } @SuppressWarnings("static-access") @Override public void execute(JobExecutionContext arg0) throws JobExecutionException { //当标记为"0"时,任务定时器不启动 if("0".equals(PropertyUtils.getProperty("emaiTimerFlag"))){ logger.info("定时器Job不启动"); return; } logger.info("定时器Job启动"); try{ if(ioc==null){ ioc = new NutIoc(new ComboIocLoader("*org.nutz.ioc.loader.json.JsonLoader", "ioc/", "*org.nutz.ioc.loader.annotation.AnnotationIocLoader", "com.wonders")); } if (mailUtils == null) { mailUtils = ioc.get(MailUtils.class); //这种提醒的邮件的“会议主题”放在下面的方法取出 (MeetingAt.getMeetingIds()) // mailUtils.sendbatch(MailUtils.getFromPerson(), MailUtils.addToperson(), "",""); // mailUtils.sendbatch(MailUtils.getFromPerson(), MailUtils.addToperson(), MeetingAt.getMeetingIds()); //发送 mailUtils.bactchSendPrompt(MailUtils.getFromPerson(),MailUtils.addToperson(),MailUtils.getAllInfo()); } }catch(Exception e){ e.printStackTrace(); }finally{ ioc.depose(); } } public static void main(String args[]){ String str[]=PropertyUtils.getProperty("sendTime").split("\\s+"); System.out.println(str[str.length-2]); } }
package com.xxx.xxx.mail.timer; import org.quartz.CronScheduleBuilder; import org.quartz.CronTrigger; import org.quartz.TriggerBuilder; import com.xxx.util.PropertyUtils; public class MailCronTrigger { public CronTrigger cronTrigger = null; public MailCronTrigger(){ //获取邮件定时发送时间 String cron = PropertyUtils.getProperty("sendTime"); CronScheduleBuilder schedule = CronScheduleBuilder.cronSchedule(cron); cronTrigger = TriggerBuilder.newTrigger().withSchedule(schedule).build(); } }
package com.xxx.tiles.extend.setup; import org.nutz.ioc.Ioc; import org.nutz.mvc.NutConfig; import org.nutz.mvc.Setup; import org.nutz.mvc.annotation.Filters; import com.jacob.com.MainSTA; import com.xxx.project.support.timer.ProjectSchedule; import com.xxx.xxx.mail.timer.MailSchedule; import com.xxx.xxx.support.timer.SignSchedule; import com.xxx.tiles.dic.DicConfigManager; @Filters public class ConfigSetup implements Setup { public void init(NutConfig nc) { Ioc ioc = nc.getIoc(); //启动邮件定时器 MailSchedule mailSchedule=ioc.get(MailSchedule.class); mailSchedule.startSchedule(); } public void destroy(NutConfig nc) { Ioc ioc = nc.getIoc(); //停止邮件定时器 MailSchedule mailSchedule=ioc.get(MailSchedule.class); mailSchedule.shutdownSchedule(); } }
@SetupBy(ConfigSetup.class)
@IocBy(type=ComboIocProvider.class,args={"*org.nutz.ioc.loader.json.JsonLoader","ioc/", "*org.nutz.ioc.loader.annotation.AnnotationIocLoader","com.wonders"}) @Modules(scanPackage=true) @SetupBy(ConfigSetup.class) @Filters({@By(type = SessionFilter.class,args={"/index"})}) @AdaptBy(type = SearchTableAdaptor.class) @Fail("ioc:errView") public class MainModule { 代码省略。。。 }
<listener> <listener-class>org.quartz.ee.servlet.QuartzInitializerListener</listener-class> </listener>
<?xml version="1.0" encoding="gb2312"?> <quartz> <job> <id>1</id> <description>定时发送短信每半小时(每30分钟的第一分钟)发送一次</description> <job-detail> <name>J1</name> <group>DEFAULT</group> <job-class>com.xxxx.tiles.sms.task.TimerSendJob</job-class> </job-detail> <trigger> <cron> <name>T1</name> <group>DEFAULT</group> <job-name>J1</job-name> <job-group>DEFAULT</job-group> <cron-expression>0 1/30 * * * ?</cron-expression> </cron> </trigger> </job> <job> <id>2</id> <description>每天23点数据对账</description> <job-detail> <name>J2</name> <group>DEFAULT</group> <job-class>com.xxxx.xxxx.xxxx.factory.DataChecking</job-class> </job-detail> <trigger> <cron> <name>T2</name> <group>DEFAULT</group> <job-name>J2</job-name> <job-group>DEFAULT</job-group> <cron-expression>0 35 13 ? * *</cron-expression> </cron> </trigger> </job> <job> <id>3</id> <description>每天12点完成心跳包的操作,作用:监控服务是否正常运行.</description> <job-detail> <name>J3</name> <group>DEFAULT</group> <job-class>com.xxxx.xxxx.dj.factory.DataCheckClear</job-class> </job-detail> <trigger> <cron> <name>T3</name> <group>DEFAULT</group> <job-name>J3</job-name> <job-group>DEFAULT</job-group> <cron-expression>0 0 12 * * ?</cron-expression> </cron> </trigger> </job> </quartz>
package com.xxx.xxx.xxx.factory; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Date; import org.apache.log4j.Logger; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import antlr.collections.List; import com.xxx.core.utils.DateUtils; import com.xxx.core.utils.SpringContextHolder; import com.xxx.xxx.dj.dao.DataSendingDao; import com.xxx.xxx.dj.entity.DataSending; import com.xxx.xxx.dj.service.ReceiveService; import com.xxx.xxx.dj.service.SendMessageService; /** * 数据对账,定时发送数据<p> */ @Component @Transactional public class DataChecking implements Job{ @Autowired private SendMessageService sendMessageService; @Autowired private DataSendingDao dataSendingDao; private static final String FAIL_FLAG = "0"; /** 日志 */ private Logger logger = Logger.getLogger(DataChecking.class); @Override public void execute(JobExecutionContext arg0) throws JobExecutionException { //获取上下文环境 ApplicationContext ctx = SpringContextHolder.getApplicationContext(); ReceiveService receiveService = ctx.getBean(ReceiveService.class); //orgName和password从政务大厅获取;统计开始时间、统计结束时间在application中配置,json在service中获取. long startSend = System.currentTimeMillis(); logger.info("==========[数据对账启动]开始========="); System.out.println("数据对账启动时间:"+DateUtils.date2String(new Date(), DateUtils.FORMAT_DATETIME)); String result = receiveService.getResult("XXXXXXX(单位名称)", "123456"); logger.info("==========数据对账结果:"+result+"==================="); logger.info("==========[数据对账启动]结束-共花费[" + (System.currentTimeMillis() - startSend) + "]毫秒=========="); //结果result(Y:发送成功,N:发送失败). //处理数据对账失败的数据 if("N".equals(result)){ this.updateDataZwdt2shzz(); } } /** * 将前置机exdata_receiving表错误信息对应的数据作为标记更新到xxxxxxx库中. */ public void updateDataZwdt2shzz(){ //======查询前置机错误信息表exdata_receiving======= Connection conn = sendMessageService.getZwdtConnection(); PreparedStatement pstmt=null; ResultSet rs = null; String sql = "SELECT ST_MEMO FROM [exdata].[dbo].[EXDATA_RECEIVING] WHERE ST_MEMO IS NOT NULL"; try { pstmt=conn.prepareStatement(sql); rs = pstmt.executeQuery(); while(rs.next()){ //取得错误信息内容 String content = rs.getString(1); //截取第一位序号ID String nmSeqId = content.substring(0, content.indexOf("SHSTSH")).trim(); String hql = " from DataSending d where d.nmSeqId = ?"; DataSending dataSending = null; java.util.List<DataSending> dataSendingList = dataSendingDao.find(hql, Integer.parseInt(nmSeqId)); for(int i=0;i<dataSendingList.size();i++){ dataSending = dataSendingList.get(0); if(dataSending != null){ //设置xxxxxx库中对账失败的数据标记为"0" dataSending.setStatus(FAIL_FLAG); //设置xxxxx库退回表中的错误信息 dataSending.setStMemo(content); //更新到数据库 dataSendingDao.saveOrUpdate(dataSending); } } } } catch (SQLException e) { e.printStackTrace(); } } }