结合SSH&Nutz框架使用定时器quartz

本文介绍了如何在Nutz和SSH框架中使用Quartz实现定时任务。包括定时任务的配置、触发器定义、业务方法实现等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本篇介绍两套框架下quartz的使用


首先下载quartz-1.6.0.jar架包,并添加到lib目录下。


一、Nutz框架中使用定时器


1.建立Schedule类:

  1. package com.xxx.xxx.mail.timer;  
  2.   
  3. import org.nutz.ioc.loader.annotation.IocBean;  
  4. import org.quartz.CronTrigger;  
  5. import org.quartz.JobBuilder;  
  6. import org.quartz.JobDetail;  
  7. import org.quartz.Scheduler;  
  8. import org.quartz.SchedulerException;  
  9. import org.quartz.SchedulerFactory;  
  10. import org.quartz.impl.StdSchedulerFactory;  
  11.   
  12. /** 
  13.  * 邮件定时器 
  14.  * @author ywx 
  15.  * 
  16.  */  
  17. @IocBean  
  18. public class MailSchedule {  
  19.     SchedulerFactory sf = null;  
  20.     Scheduler sched = null;  
  21.     JobDetail job = null;  
  22.     /** 
  23.      * 启动定时器 
  24.      */  
  25.     public void startSchedule(){  
  26.         sf = new StdSchedulerFactory();  
  27.         try {  
  28.             sched=sf.getScheduler();  
  29.             job=JobBuilder.newJob(MailJob.class).build();  
  30.             CronTrigger cTrigger=new MailCronTrigger().cronTrigger;  
  31.             sched.scheduleJob(job, cTrigger);  
  32.             sched.start();  
  33.         } catch (SchedulerException e) {  
  34.             e.printStackTrace();  
  35.         }  
  36.     }  
  37.     /** 
  38.      * 停止定时器 
  39.      */  
  40.     public void shutdownSchedule() {  
  41.         if (null != sched) {  
  42.             try {  
  43.                 sched.shutdown();  
  44.             } catch (SchedulerException e) {  
  45.                 e.printStackTrace();  
  46.             }  
  47.         }  
  48.     }  
  49.   
  50. }  

2.写好定时需要做的事情:

  1. package com.xxx.xxx.mail.timer;  
  2.   
  3. import java.util.Calendar;  
  4. import java.util.Date;  
  5.   
  6. import org.nutz.ioc.Ioc;  
  7. import org.nutz.ioc.impl.NutIoc;  
  8. import org.nutz.ioc.loader.combo.ComboIocLoader;  
  9. import org.nutz.log.Log;  
  10. import org.nutz.log.Logs;  
  11. import org.quartz.Job;  
  12. import org.quartz.JobExecutionContext;  
  13. import org.quartz.JobExecutionException;  
  14.   
  15. import com.xxx.xxx.at.MeetingAt;  
  16. import com.xxx.util.MailUtils;  
  17. import com.xxx.util.PropertyUtils;  
  18.   
  19. /** 
  20.  * 定时器执行任务内容 
  21.  * @author ywx 
  22.  * 
  23.  */  
  24. public class MailJob implements Job{  
  25.       
  26.     Ioc ioc = null;  
  27.     private Log logger = Logs.get();  
  28.       
  29.     private MailUtils mailUtils=null;  
  30.   
  31.       
  32.     /** 
  33.      * 获取当前日期是星期几 
  34.      * @param time 当前日期 
  35.      * @return 
  36.      * @throws Exception 
  37.      */  
  38.     public static String isFriday(Date time){  
  39.         Calendar c=Calendar.getInstance();  
  40.         c.setTime(time);  
  41.         int dayForWeek=0;  
  42.         if(c.get(Calendar.DAY_OF_WEEK)==1){  
  43.             dayForWeek=7;  
  44.         }else{  
  45.             dayForWeek=c.get(Calendar.DAY_OF_WEEK)-1;  
  46.         }  
  47.         return String.valueOf(dayForWeek);  
  48.     }  
  49.   
  50.   
  51.     @SuppressWarnings("static-access")  
  52.     @Override  
  53.     public void execute(JobExecutionContext arg0) throws JobExecutionException {  
  54.         //当标记为"0"时,任务定时器不启动  
  55.         if("0".equals(PropertyUtils.getProperty("emaiTimerFlag"))){  
  56.             logger.info("定时器Job不启动");  
  57.             return;  
  58.         }  
  59.         logger.info("定时器Job启动");  
  60.         try{  
  61.             if(ioc==null){  
  62.                 ioc = new NutIoc(new ComboIocLoader("*org.nutz.ioc.loader.json.JsonLoader""ioc/""*org.nutz.ioc.loader.annotation.AnnotationIocLoader",  
  63.                         "com.wonders"));  
  64.             }  
  65.             if (mailUtils == null) {  
  66.                 mailUtils = ioc.get(MailUtils.class);  
  67.                 //这种提醒的邮件的“会议主题”放在下面的方法取出 (MeetingAt.getMeetingIds())  
  68. //              mailUtils.sendbatch(MailUtils.getFromPerson(), MailUtils.addToperson(), "","");  
  69. //              mailUtils.sendbatch(MailUtils.getFromPerson(), MailUtils.addToperson(), MeetingAt.getMeetingIds());  
  70.                 //发送  
  71.                 mailUtils.bactchSendPrompt(MailUtils.getFromPerson(),MailUtils.addToperson(),MailUtils.getAllInfo());  
  72.             }  
  73.         }catch(Exception e){  
  74.             e.printStackTrace();  
  75.         }finally{  
  76.             ioc.depose();  
  77.         }  
  78.     }  
  79.     public static void main(String args[]){  
  80.         String str[]=PropertyUtils.getProperty("sendTime").split("\\s+");  
  81.         System.out.println(str[str.length-2]);  
  82.     }  
  83. }  

3.在什么时候执行任务:

  1. package com.xxx.xxx.mail.timer;  
  2.   
  3. import org.quartz.CronScheduleBuilder;  
  4. import org.quartz.CronTrigger;  
  5. import org.quartz.TriggerBuilder;  
  6.   
  7. import com.xxx.util.PropertyUtils;  
  8.   
  9. public class MailCronTrigger {  
  10.     public CronTrigger cronTrigger = null;  
  11.     public MailCronTrigger(){  
  12.         //获取邮件定时发送时间  
  13.         String cron = PropertyUtils.getProperty("sendTime");  
  14.         CronScheduleBuilder schedule = CronScheduleBuilder.cronSchedule(cron);  
  15.         cronTrigger = TriggerBuilder.newTrigger().withSchedule(schedule).build();  
  16.     }  
  17.   
  18. }  

4.写好定时器之后,还有配置服务启动配置:

  1. package com.xxx.tiles.extend.setup;  
  2.   
  3. import org.nutz.ioc.Ioc;  
  4. import org.nutz.mvc.NutConfig;  
  5. import org.nutz.mvc.Setup;  
  6. import org.nutz.mvc.annotation.Filters;  
  7.   
  8. import com.jacob.com.MainSTA;  
  9. import com.xxx.project.support.timer.ProjectSchedule;  
  10. import com.xxx.xxx.mail.timer.MailSchedule;  
  11. import com.xxx.xxx.support.timer.SignSchedule;  
  12. import com.xxx.tiles.dic.DicConfigManager;  
  13.   
  14. @Filters  
  15. public class ConfigSetup implements Setup {  
  16.   
  17.     public void init(NutConfig nc) {  
  18.         Ioc ioc = nc.getIoc();  
  19.           
  20.         //启动邮件定时器  
  21.         MailSchedule mailSchedule=ioc.get(MailSchedule.class);  
  22.         mailSchedule.startSchedule();  
  23.           
  24.     }  
  25.   
  26.     public void destroy(NutConfig nc) {  
  27.         Ioc ioc = nc.getIoc();  
  28.         //停止邮件定时器   
  29.         MailSchedule mailSchedule=ioc.get(MailSchedule.class);  
  30.         mailSchedule.shutdownSchedule();  
  31.     }  
  32.   
  33. }  

5.Nutz的MainModule类上加上,作用:启动服务时开启定时器。

  1. @SetupBy(ConfigSetup.class)  


示例如下:

  1. @IocBy(type=ComboIocProvider.class,args={"*org.nutz.ioc.loader.json.JsonLoader","ioc/",  
  2.     "*org.nutz.ioc.loader.annotation.AnnotationIocLoader","com.wonders"})  
  3. @Modules(scanPackage=true)  
  4. @SetupBy(ConfigSetup.class)  
  5. @Filters({@By(type = SessionFilter.class,args={"/index"})})  
  6. @AdaptBy(type = SearchTableAdaptor.class)  
  7. @Fail("ioc:errView")  
  8. public class MainModule { 代码省略。。。  }  

附言:以上的实例就是这么简单粗暴实用。。。。。。




二、SSH框架中使用定时器


SSH框架中使用定时器比较Nutz来说要简单明了,不要去写CronTrigger和Schedule了;使用有两种方式(本篇文章具体介绍一种方式足以)。

1. 在web.xml中配置监听quartz:

  1. <listener>   
  2.        <listener-class>org.quartz.ee.servlet.QuartzInitializerListener</listener-class>   
  3. </listener>  

2.添加quartz_jobs.xml文件,并在该配置文件中增加job节点信息:

  1. <?xml version="1.0" encoding="gb2312"?>  
  2. <quartz>  
  3. <job>  
  4.     <id>1</id>  
  5.     <description>定时发送短信每半小时(每30分钟的第一分钟)发送一次</description>  
  6.     <job-detail>  
  7.         <name>J1</name>  
  8.         <group>DEFAULT</group>  
  9.         <job-class>com.xxxx.tiles.sms.task.TimerSendJob</job-class>  
  10.     </job-detail>  
  11.     <trigger>  
  12.         <cron>  
  13.             <name>T1</name>  
  14.             <group>DEFAULT</group>  
  15.             <job-name>J1</job-name>  
  16.             <job-group>DEFAULT</job-group>  
  17.             <cron-expression>0 1/30 * * * ?</cron-expression>  
  18.         </cron>  
  19.     </trigger>  
  20. </job>  
  21. <job>  
  22.     <id>2</id>  
  23.     <description>每天23点数据对账</description>  
  24.     <job-detail>  
  25.         <name>J2</name>  
  26.         <group>DEFAULT</group>  
  27.         <job-class>com.xxxx.xxxx.xxxx.factory.DataChecking</job-class>  
  28.     </job-detail>  
  29.     <trigger>  
  30.         <cron>  
  31.             <name>T2</name>  
  32.             <group>DEFAULT</group>  
  33.             <job-name>J2</job-name>  
  34.             <job-group>DEFAULT</job-group>  
  35.             <cron-expression>0 35 13 ? * *</cron-expression>  
  36.         </cron>  
  37.     </trigger>  
  38. </job>  
  39. <job>  
  40.     <id>3</id>  
  41.     <description>每天12点完成心跳包的操作,作用:监控服务是否正常运行.</description>  
  42.     <job-detail>  
  43.         <name>J3</name>  
  44.         <group>DEFAULT</group>  
  45.         <job-class>com.xxxx.xxxx.dj.factory.DataCheckClear</job-class>  
  46.     </job-detail>  
  47.     <trigger>  
  48.         <cron>  
  49.             <name>T3</name>  
  50.             <group>DEFAULT</group>  
  51.             <job-name>J3</job-name>  
  52.             <job-group>DEFAULT</job-group>  
  53.             <cron-expression>0 0 12 * * ?</cron-expression>  
  54.         </cron>  
  55.     </trigger>  
  56. </job>  
  57. </quartz>  

3. 定时业务方法:

  1. package com.xxx.xxx.xxx.factory;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.PreparedStatement;  
  5. import java.sql.ResultSet;  
  6. import java.sql.SQLException;  
  7. import java.util.Date;  
  8.   
  9. import org.apache.log4j.Logger;  
  10. import org.quartz.Job;  
  11. import org.quartz.JobExecutionContext;  
  12. import org.quartz.JobExecutionException;  
  13. import org.springframework.beans.factory.annotation.Autowired;  
  14. import org.springframework.context.ApplicationContext;  
  15. import org.springframework.stereotype.Component;  
  16. import org.springframework.transaction.annotation.Transactional;  
  17.   
  18. import antlr.collections.List;  
  19.   
  20. import com.xxx.core.utils.DateUtils;  
  21. import com.xxx.core.utils.SpringContextHolder;  
  22. import com.xxx.xxx.dj.dao.DataSendingDao;  
  23. import com.xxx.xxx.dj.entity.DataSending;  
  24. import com.xxx.xxx.dj.service.ReceiveService;  
  25. import com.xxx.xxx.dj.service.SendMessageService;  
  26.   
  27. /** 
  28.  * 数据对账,定时发送数据<p> 
  29.  */  
  30. @Component  
  31. @Transactional  
  32. public class DataChecking implements Job{  
  33.   
  34.     @Autowired  
  35.     private SendMessageService sendMessageService;  
  36.     @Autowired  
  37.     private DataSendingDao dataSendingDao;  
  38.       
  39.     private static final String FAIL_FLAG = "0";  
  40.       
  41.       
  42.     /** 日志 */  
  43.     private Logger logger = Logger.getLogger(DataChecking.class);  
  44.    
  45.     @Override  
  46.     public void execute(JobExecutionContext arg0) throws JobExecutionException {  
  47.         //获取上下文环境  
  48.         ApplicationContext ctx = SpringContextHolder.getApplicationContext();  
  49.         ReceiveService receiveService = ctx.getBean(ReceiveService.class);  
  50.           
  51.         //orgName和password从政务大厅获取;统计开始时间、统计结束时间在application中配置,json在service中获取.  
  52.         long startSend = System.currentTimeMillis();  
  53.         logger.info("==========[数据对账启动]开始=========");  
  54.         System.out.println("数据对账启动时间:"+DateUtils.date2String(new Date(), DateUtils.FORMAT_DATETIME));  
  55.         String result = receiveService.getResult("XXXXXXX(单位名称)""123456");  
  56.         logger.info("==========数据对账结果:"+result+"===================");   
  57.         logger.info("==========[数据对账启动]结束-共花费[" + (System.currentTimeMillis() - startSend) + "]毫秒==========");  
  58.           
  59.         //结果result(Y:发送成功,N:发送失败).  
  60.         //处理数据对账失败的数据  
  61.         if("N".equals(result)){  
  62.             this.updateDataZwdt2shzz();  
  63.         }  
  64.     }  
  65.     /** 
  66.      * 将前置机exdata_receiving表错误信息对应的数据作为标记更新到xxxxxxx库中. 
  67.      */  
  68.     public void updateDataZwdt2shzz(){  
  69.         //======查询前置机错误信息表exdata_receiving=======  
  70.         Connection conn = sendMessageService.getZwdtConnection();  
  71.         PreparedStatement pstmt=null;  
  72.         ResultSet rs = null;   
  73.         String sql = "SELECT ST_MEMO FROM [exdata].[dbo].[EXDATA_RECEIVING] WHERE ST_MEMO IS NOT NULL";  
  74.            
  75.         try {  
  76.             pstmt=conn.prepareStatement(sql);  
  77.             rs = pstmt.executeQuery();  
  78.             while(rs.next()){  
  79.                 //取得错误信息内容  
  80.                 String content = rs.getString(1);  
  81.                 //截取第一位序号ID    
  82.                 String nmSeqId = content.substring(0, content.indexOf("SHSTSH")).trim();  
  83.                 String hql = " from DataSending d where d.nmSeqId = ?";  
  84.                 DataSending dataSending = null;  
  85.                 java.util.List<DataSending> dataSendingList = dataSendingDao.find(hql, Integer.parseInt(nmSeqId));  
  86.                 for(int i=0;i<dataSendingList.size();i++){  
  87.                     dataSending = dataSendingList.get(0);  
  88.                     if(dataSending != null){  
  89.                         //设置xxxxxx库中对账失败的数据标记为"0"  
  90.                         dataSending.setStatus(FAIL_FLAG);  
  91.                         //设置xxxxx库退回表中的错误信息   
  92.                         dataSending.setStMemo(content);  
  93.                         //更新到数据库  
  94.                         dataSendingDao.saveOrUpdate(dataSending);  
  95.                     }   
  96.                 }  
  97.             }  
  98.         } catch (SQLException e) {  
  99.             e.printStackTrace();  
  100.         }  
  101.     }  
  102. }  

附言:相对Nutz框架来说,ssh中使用定时器方便多了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值