Quartz

//第一步
public static void main(String args[]) {
SchedulerManage.start();//启动定时器
}


//第二步
package com.lolaage.quartz;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.JobDetail;

import com.lolaage.common.GlobalConstValue;
import com.lolaage.entity.newdata.QuartzEntity;

public class SchedulerManage {
public static Logger logger = Logger.getLogger(SchedulerManage.class);
private static Scheduler sched = null;

public SchedulerManage(){

}

public static void addJob(QuartzEntity quartz) {

try {
@SuppressWarnings("unchecked")
JobDetail job = JobBuilder.newJob(quartz.getJob_class())
.withIdentity(quartz.getJob_name(), quartz.getJob_group())
.build();

Trigger trigger = TriggerBuilder
.newTrigger()
.withIdentity(quartz.getJob_trigger(),
quartz.getJob_group())
.withSchedule(
CronScheduleBuilder.cronSchedule(quartz
.getCron_expression()))
.forJob(quartz.getJob_name(), quartz.getJob_group())
.build();

sched.scheduleJob(job, trigger); // 添加工作

} catch (Exception e) {
e.printStackTrace();
}
}

@SuppressWarnings("unchecked")
public ArrayList<QuartzEntity> initReadConfig() {
SAXReader reader = new SAXReader();
Document doc;
try {
doc = reader.read(GlobalConstValue.QUARTZ_XML_FILE);
Element root = doc.getRootElement();
List<Element> elements = root.selectNodes("/quartz/job");
ArrayList<QuartzEntity> quartzArray = new ArrayList<QuartzEntity>();
QuartzEntity quartz = null;
for (Element jobElement : elements) {
quartz = new QuartzEntity();
quartz.setJob_name(jobElement.elementTextTrim("job-name"));
quartz.setJob_group(jobElement.elementTextTrim("job-group"));
quartz.setJob_trigger(jobElement.elementTextTrim("job-trigger"));
quartz.setCron_expression(jobElement
.elementTextTrim("cron-expression"));

ClassLoader commonLoader = this.getClass().getClassLoader();
quartz.setJob_class(commonLoader.loadClass(jobElement
.elementTextTrim("job-class")));
quartzArray.add(quartz);
}
return quartzArray;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {

e.printStackTrace();
}
return null;

}
public static void start() throws SchedulerException{
logger.debug("SchedulerManage start............");
sched = new StdSchedulerFactory().getScheduler();

SchedulerManage s = new SchedulerManage();
ArrayList<QuartzEntity> quartzArray = s.initReadConfig();
if (quartzArray == null)
return;
else {
for (QuartzEntity quartz : quartzArray) {
SchedulerManage.addJob(quartz);
}
sched.start();
}
}

// public static void start() {
//
// Scheduler sched;
// try {
// // sched = schedFact.getScheduler();
// sched = new StdSchedulerFactory().getScheduler();
//
// JobDetail jobDetail = JobBuilder.newJob(GetEventInfoJob.class)
// .withIdentity("GetEventInfo", "GetEventInfoGroup").build();
//
// Trigger trigger = TriggerBuilder
// .newTrigger()
// .withIdentity("GetEventInfoTrigger", "GetEventInfoGroup")
// .withSchedule(
// CronScheduleBuilder
// .cronSchedule("0 0/5 * * * ?"))
// .forJob("GetEventInfo", "GetEventInfoGroup").build();
//
// sched.scheduleJob(jobDetail, trigger); // 添加工作
//
// sched.start();
// // sched.shutdown();
//
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// }
}


//第三步
package com.lolaage.quartz;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramSocket;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import com.lolaage.common.GlobalConstValue;
import com.lolaage.common.MailType;
import com.lolaage.dals.distributetransaction.DistributeTransaction;
import com.lolaage.dals.sessionmanager.SessionPoint;
import com.lolaage.entity.newdata.Notice;
import com.lolaage.entity.newdata.NoticeUser;
import com.lolaage.entity.newdata.TMailBox;
import com.lolaage.entity.resBean.X101ResBean;
import com.lolaage.entity.struct.ParamStruct;
import com.lolaage.entity.struct.PublicNoticeStruct;
import com.lolaage.entity.struct.TTime;
import com.lolaage.exception.DataVersionSQLException;
import com.lolaage.factory.PostManager;
import com.lolaage.newdao.DepartmentDao;
import com.lolaage.newdao.NoticeDao;
import com.lolaage.newdao.NoticeUserDao;
import com.lolaage.newdao.UserDao;
import com.lolaage.newdao.impl.DepartmentDaoImpl;
import com.lolaage.newdao.impl.GlobalCompanyDaoImpl;
import com.lolaage.newdao.impl.NoticeDaoImpl;
import com.lolaage.newdao.impl.NoticeUserDaoImpl;
import com.lolaage.newdao.impl.UserDaoImpl;
import com.lolaage.util.CalendarUtil;
import com.lolaage.util.FrameUtil;

public class NoticeJob implements Job {

/**
* logger
*/
public static Logger logger = Logger.getLogger(NoticeJob.class);

public void execute(JobExecutionContext arg0) throws JobExecutionException {

DatagramSocket socket = (DatagramSocket) arg0.getJobDetail()
.getJobDataMap().get("socket");
ParamStruct paramStruct = new ParamStruct();
paramStruct.setSocket(socket);
//获取企业ids
SessionPoint sessionPoint=new SessionPoint().start();
DistributeTransaction distributeTransaction=new DistributeTransaction().beginDistributeTransaction();
try{
GlobalCompanyDaoImpl globalCompanyDao = new GlobalCompanyDaoImpl(GlobalConstValue.ZERO, distributeTransaction, sessionPoint);
List<Long> companyIdLst = globalCompanyDao.getAllCompanyIds();
distributeTransaction.commitDistributeTransaction();
//给每个企业发送通告
if(companyIdLst != null && companyIdLst.size() > 0 ){
for(Long companyId:companyIdLst){
paramStruct.setCompanyId(companyId);
sendNotice(paramStruct);
}
}
}catch(Exception ex){
distributeTransaction.rollbackDistributeTransaction();
logger.error(ex.getCause(), ex);
ex.printStackTrace();
}finally{
//释放连接
sessionPoint.end();
}

}
public void sendNotice(ParamStruct paramStruct){
SessionPoint sessionPoint=new SessionPoint().start();
DistributeTransaction distributeTransaction=new DistributeTransaction().beginDistributeTransaction();
NoticeDao noticeDao = new NoticeDaoImpl(paramStruct.getCompanyId(),distributeTransaction,sessionPoint);
NoticeUserDao noticeUserDao=new NoticeUserDaoImpl(paramStruct.getCompanyId(),distributeTransaction,sessionPoint);
UserDao userDao=new UserDaoImpl(paramStruct.getCompanyId(),distributeTransaction,sessionPoint);
try {
Map<Long,Notice> noticeMap=null;
List<NoticeUser> noticeUserList=noticeUserDao.getNoticeUserByStatus();
if(noticeUserList!=null && noticeUserList.size()>0){
noticeMap=new HashMap<Long,Notice>();
for(NoticeUser noticeUser:noticeUserList){
Notice notice=null;
if(noticeMap.containsKey(noticeUser.getNoticeId())){
notice=noticeMap.get(noticeUser.getNoticeId());
}else{
notice=noticeDao.getNoticeById(noticeUser.getNoticeId());
if(notice!=null){
noticeMap.put(noticeUser.getNoticeId(),notice);
}
}

if(notice!=null){
PublicNoticeStruct publicNotice = new PublicNoticeStruct();
publicNotice.setMsgId((int)notice.getId());
if(notice.getCreaterId()!=0){
try {
publicNotice.setPublisherName(userDao.getNicknameByUserId(notice.getCreaterId()));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

publicNotice.setMsgTime(notice.getSendTime());
publicNotice.setDetail(notice.getContent());
publicNotice.setTitle(notice.getTitle());
//X101对象
X101ResBean resBean = new X101ResBean();
resBean.setPublicNotice(publicNotice);

TMailBox mail = FrameUtil.generateMail(paramStruct.getCompanyId(),noticeUser.getUserId(), "X", 101,
(byte)MailType.MAIL_TYPE_NORMAL, resBean.toByteArray());
PostManager.postMail(mail, paramStruct);
noticeUserDao.updateStatus(noticeUser.getId(),1);
}
}
}

//commitDistributeTransaction
distributeTransaction.commitDistributeTransaction();

} catch (SQLException e1) {
distributeTransaction.rollbackDistributeTransaction();
e1.printStackTrace();
}
catch (UnsupportedEncodingException e) {
distributeTransaction.rollbackDistributeTransaction();
e.printStackTrace();
} catch (DataVersionSQLException e) {
distributeTransaction.rollbackDistributeTransaction();
e.printStackTrace();
} catch (IOException e) {
distributeTransaction.rollbackDistributeTransaction();
e.printStackTrace();
} finally {
sessionPoint.end();
}
}
}


//第四步(Quartz.xml)

<?xml version="1.0" encoding="UTF-8"?>
<quartz>
<job>
<job-name>GetEventInfo</job-name>
<job-group>GetEventInfoGroup</job-group>
<job-trigger>GetEventInfoTrigger</job-trigger>
<cron-expression>0 0/100 * * * ?</cron-expression>
<job-class>com.lolaage.quartz.GetEventInfoJob</job-class>
</job>
<job>
<job-name>SendPublicNotice</job-name>
<job-group>PublicNoticeGroup</job-group>
<job-trigger>SendPublicNoticeTrigger</job-trigger>
<cron-expression>0 0/100 * * * ?</cron-expression>
<job-class>com.lolaage.quartz.NoticeJob</job-class>
</job>
</quartz>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值