SSH&Nutz框架使用定時器quartz
阿新 • • 發佈:2019-01-11
作者:vashon
時間:20151226
本篇介紹兩套框架下quartz的使用
首先下載quartz-1.6.0.jar架包,並新增到lib目錄下。
一、Nutz框架中使用定時器
1.建立Schedule類:
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(); } } } }
2.寫好定時需要做的事情:
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]); } }
3.在什麼時候執行任務:
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();
}
}
4.寫好定時器之後,還有配置服務啟動配置:
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();
}
}
5.Nutz的MainModule類上加上,作用:啟動服務時開啟定時器。
@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 { 程式碼省略。。。 }
附言:以上的例項就是這麼簡單粗暴實用。。。。。。
二、SSH框架中使用定時器
SSH框架中使用定時器比較Nutz來說要簡單明瞭,不要去寫CronTrigger和Schedule了;使用有兩種方式(本篇文章具體介紹一種方式足以)。
1. 在web.xml中配置監聽quartz:
<listener>
<listener-class>org.quartz.ee.servlet.QuartzInitializerListener</listener-class>
</listener>
2.新增quartz_jobs.xml檔案,並在該配置檔案中增加job節點資訊:
<?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>
3. 定時業務方法:
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();
}
}
}
附言:相對Nutz框架來說,ssh中使用定時器方便多了。