修改短信发送任务

This commit is contained in:
gityjf 2021-01-29 15:33:45 +08:00
parent 7379f6f404
commit a2be8ebd25
2 changed files with 318 additions and 338 deletions

View File

@ -1,81 +1,62 @@
package com.tenwa.message;
import com.alibaba.fastjson.JSONObject;
import com.amarsoft.are.jbo.*;
import com.tenwa.lease.util.SendMessageUtil;
import jbo.com.tenwa.lease.comm.LB_SMS_NOTICE_TASKS;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import java.text.SimpleDateFormat;
import java.util.Date;
import jbo.com.tenwa.lease.comm.LB_SMS_NOTICE_TASKS;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
import com.amarsoft.are.jbo.BizObject;
import com.amarsoft.are.jbo.BizObjectManager;
import com.amarsoft.are.jbo.JBOException;
import com.amarsoft.are.jbo.JBOFactory;
import com.amarsoft.are.jbo.JBOTransaction;
import com.tenwa.lease.util.SendMessageUtil;
public class JobSendMessage implements Job{
private Log logger = LogFactory.getLog(this.getClass());
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
JBOTransaction tx = null;
String smsnoticeid = null;
try {
tx= JBOFactory.createJBOTransaction();
Scheduler sch = StdSchedulerFactory.getDefaultScheduler();
Trigger tri = context.getTrigger();
JobDetail jobDetail = sch.getJobDetail(tri.getJobKey());
smsnoticeid = context.getJobDetail().getJobDataMap().getString("smsnoticeid");
logger.info("short message running..... LB_SMS_NOTICE_TASKS[ID]: "+smsnoticeid);
BizObjectManager bomNotice = JBOFactory.getBizObjectManager(LB_SMS_NOTICE_TASKS.CLASS_NAME,tx);
BizObject notice = bomNotice.createQuery("id=:id").setParameter("id", jobDetail.getJobDataMap().getString("smsnoticeid")).getSingleResult(true);
int max = 1;//短信发送失败重新发送次数
BizObject notice = bomNotice.createQuery("id=:id").setParameter("id", smsnoticeid).getSingleResult(true);
if(notice != null){
if(notice.getAttribute("send_flag").getInt() == 0){
String result = null;
long pauseTime = 0;
boolean flagErrStatus = true;
try {
for(int i=0;i<max;i++){
result = SendMessageUtil.sendMessageByHttpClient(notice.getAttribute("phone_number").getString(), notice.getAttribute("sms_content").getString());
if(i>0){
break;
}
if("0".equals(result.substring(0,1))){
break;
}else{
logger.error("短信发送失败,5秒后重新发送...");
sch.pauseTrigger(tri.getKey());
pauseTime = new Date().getTime();
}
while(true){
if(new Date().getTime()-pauseTime >=5000){
sch.resumeTrigger(tri.getKey());
break;
}
}
}
result = SendMessageUtil.sendMessageByHttpClient(notice.getAttribute("phone_number").getString(), notice.getAttribute("sms_content").getString());
if(!result.matches("^[0-9].*")){
JSONObject jsonObject = JSONObject.parseObject(result);
if(jsonObject.getIntValue("status")==100){
flagErrStatus = false;
result = "全部成功";
}else{
result = getResultCodeInfoNew(jsonObject.getString("status"));
}
}
} catch (Exception e) {
logger.error("短信发送任务执行失败", e);
logger.error("短信发送任务执行失败,LB_SMS_NOTICE_TASKS[ID] : "+smsnoticeid, e);
result = "发送失败,发送遇到异常:" + e.getMessage();
}
notice.setAttributeValue("sms_type", "IMMEDIATELY");
notice.setAttributeValue("send_result", getResultCodeInfo(result));
notice.setAttributeValue("send_result", result);
notice.setAttributeValue("send_time", sdf.format(new Date()));
notice.setAttributeValue("send_flag", 1);
notice.setAttributeValue("send_flag", flagErrStatus ? 0 : 1);
bomNotice.saveObject(notice);
}
bomNotice.saveObject(notice);
}
tx.commit();
} catch (Exception e) {
e.printStackTrace();
logger.error("short message error LB_SMS_NOTICE_TASKS[ID] : "+smsnoticeid ,e);
try {
tx.rollback();
} catch (JBOException e1) {
@ -83,7 +64,26 @@ public class JobSendMessage implements Job{
}
}
}
public static String getResultCodeInfoNew(String code){
String codeMessage = "";
switch(code){
case "101": codeMessage = "参数错误"; break;
case "102": codeMessage = "号码错误"; break;
case "103": codeMessage = "当日余量不足"; break;
case "104": codeMessage = "请求超时"; break;
case "105": codeMessage = "用户余量不足"; break;
case "106": codeMessage = "非法用户"; break;
case "107": codeMessage = "提交号码超限"; break;
case "111": codeMessage = "签名不合法"; break;
case "120": codeMessage = "内容长度超长请不要超过500个字"; break;
case "121": codeMessage = "内容中有屏蔽词"; break;
case "131": codeMessage = "IP非法"; break;
default : codeMessage = code ; break;
}
return codeMessage;
}
public static String getResultCodeInfo(String code){
String codeMessage = "";
switch(code){

View File

@ -1,297 +1,277 @@
package com.tenwa.message;
import com.amarsoft.are.ARE;
import com.amarsoft.are.jbo.*;
import com.amarsoft.awe.util.ASResultSet;
import com.amarsoft.awe.util.SqlObject;
import com.amarsoft.awe.util.Transaction;
import com.tenwa.quartz.DateUtil;
import com.tenwa.reckon.util.UUIDUtil;
import jbo.com.tenwa.lease.comm.LB_SMS_NOTICE_TASKS;
import jbo.sys.MSG_CONFIG;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import jbo.com.tenwa.lease.comm.LB_SMS_NOTICE_TASKS;
import jbo.sys.MSG_CONFIG;
public class QuartzJobMsg implements Job {
import org.quartz.CronExpression;
import org.quartz.CronScheduleBuilder;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.quartz.ListenerManager;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.matchers.KeyMatcher;
public static final String MSG_GROUP_NAME = "MSG_DEFAULT_GROUP";
import com.amarsoft.are.jbo.BizObject;
import com.amarsoft.are.jbo.BizObjectManager;
import com.amarsoft.are.jbo.JBOException;
import com.amarsoft.are.jbo.JBOFactory;
import com.amarsoft.are.jbo.JBOTransaction;
import com.amarsoft.awe.util.ASResultSet;
import com.amarsoft.awe.util.SqlObject;
import com.amarsoft.awe.util.Transaction;
import com.tenwa.quartz.DateUtil;
import com.tenwa.quartz.JobListenerImpl;
import com.tenwa.quartz.TriggerListenerImpl;
import com.tenwa.reckon.util.UUIDUtil;
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
JBOTransaction tx = null;
JBOTransaction inner_tx = null;
try {
tx = JBOFactory.createJBOTransaction();
Transaction tran = Transaction.createTransaction(tx);
Trigger trigger = context.getTrigger();
JobDataMap data = context.getJobDetail().getJobDataMap();
//获取主键
String id = data.getString("id");
//获取sql语句
String msgsql = data.getString("msgSql");
//获取关键字
String msgsqlparam = data.getString("msgsqlparam");
//获取短信内容
String msgcontent = data.getString("msgcontent");
//获取触发方式
String triggermode = data.getString("triggermode");
//获取短信发送时间类型短信延迟发送天数短信发送时间点
String msgsendtype = data.getString("msgsendtype");//短信发送类型
String msgsendtime = "";//短信发送时间点
Date timeSet = null;
boolean checkTime = false;
Date timeNow = new Date();
if (data.getString("msgsendtime") != null) {
msgsendtime = data.getString("msgsendtime");
timeSet = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(new SimpleDateFormat("yyyy-MM-dd").format(timeNow) + " " + msgsendtime);
}
String delayday = "";//延迟发送天数
if (data.getString("delayday") != null) {
delayday = data.getString("delayday");
}
//获得过期是否执行
String isoverdateexecute = data.getString("isoverdateexecute");
//获取短信类型
String msgtype = data.getString("msgType");
if ("Tl_Business".equals(msgtype) || "Tl_ChangeBusiness".equals(msgtype) || "Tl_MakeContract".equals(msgtype) || "Tl_ChangeContract".equals(msgtype) || "Tl_AfterRenting".equals(msgtype)) {
msgcontent = msgcontent.replace("@", "=");
}
//获取是否按日期去重
String isrepatebydate = data.getString("isrepeatbydate");
//获取短信替换参数
int oldlength = msgcontent.length();
int newlength = msgcontent.replace("}", "").length();
String[] params = new String[oldlength - newlength];
if (params.length > 0) {
int index = 0;
for (int i = 0; i < params.length; i++) {
int start = msgcontent.indexOf("{", index);
int end = msgcontent.indexOf("}", index);
params[i] = msgcontent.substring(start + 1, end);
index = end + 1;
}
}
JBOFactory.getBizObjectManager(MSG_CONFIG.CLASS_NAME, tx).createQuery("update O set previous_fire_time=:previousFireTime , next_fire_time=:nextFireTime where id='" + id + "'")
.setParameter("previousFireTime", trigger.getPreviousFireTime().getTime())
.setParameter("nextFireTime", trigger.getNextFireTime() == null ? "" : String.valueOf(trigger.getNextFireTime().getTime())).executeUpdate();
ASResultSet rs = tran.getASResultSet(new SqlObject(msgsql));
Scheduler scheduler = getScheduler();
Transaction inner_tran = null;
while (rs.next()) {
boolean flag = false;
for (int p = 0; p < params.length; p++) {
if (rs.getString(params[p]) == null) {
flag = true;
}
}
if (flag) {
continue;
}
String rsMsgContent = msgcontent;
Object phonenumber = rs.getString("phonenumber");
if (phonenumber == null || phonenumber.toString().length() != 11) {
continue;
}
//新起数据库连接
inner_tx = JBOFactory.createJBOTransaction();
inner_tran = Transaction.createTransaction(inner_tx);
//查询关联记录
String sql = "select * from msg_send_relative where 1=1 ";
String[] sqlparams = msgsqlparam.split("&");
if (sqlparams.length > 0) {
for (int i = 0; i < sqlparams.length; i++) {
sql += "and " + sqlparams[i] + "='" + rs.getString(sqlparams[i]).toString() + "' ";
}
}
if (isrepatebydate.equals("yes")) {//根据日期去重
sql += "and inputtime='" + rs.getString("checkdate") + "'";
}
if (msgtype.startsWith("holiday") || msgtype.startsWith("birthday")) {//如果是生日祝福和节假日祝福必须添加短信类型和日期条件筛选
sql += "and msg_type='" + msgtype + "' and inputtime='" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "'";
} else {
sql += "and msg_type='" + msgtype + "'";
}
sql = sql.replaceAll(":", "");
SqlObject so = new SqlObject(sql);
so.setRunSql(so.getRunSql().replaceAll("", ":"));
ASResultSet msgSend = inner_tran.getASResultSet(so);
public class QuartzJobMsg implements Job{
public static final String MSG_GROUP_NAME = "MSG_DEFAULT_GROUP";
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
JBOTransaction tx = null;
try{
tx= JBOFactory.createJBOTransaction();
Transaction tran = Transaction.createTransaction(tx);
Scheduler sch = StdSchedulerFactory.getDefaultScheduler();
Trigger trigger = context.getTrigger();
JobDetail detail = sch.getJobDetail(trigger.getJobKey());
JobDataMap data = detail.getJobDataMap();
//获取主键
String id = data.getString("id");
//获取sql语句
String msgsql = data.getString("msgSql");
//获取关键字
String msgsqlparam = data.getString("msgsqlparam");
//获取短信内容
String msgcontent = data.getString("msgcontent");
//获取触发方式
String triggermode = data.getString("triggermode");
//获取短信发送时间类型短信延迟发送天数短信发送时间点
String msgsendtype = data.getString("msgsendtype");//短信发送类型
String msgsendtime = "";//短信发送时间点
Date timeSet = null;
boolean checkTime = false;
Date timeNow = new Date();
if(data.getString("msgsendtime") != null){
msgsendtime = data.getString("msgsendtime");
timeSet = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(new SimpleDateFormat("yyyy-MM-dd").format(timeNow)+" "+msgsendtime);
}
String delayday = "";//延迟发送天数
if(data.getString("delayday") != null){
delayday = data.getString("delayday");
}
//获得过期是否执行
String isoverdateexecute = data.getString("isoverdateexecute");
//获取短信类型
String msgtype = data.getString("msgType");
if("Tl_Business".equals(msgtype) || "Tl_ChangeBusiness".equals(msgtype)|| "Tl_MakeContract".equals(msgtype)|| "Tl_ChangeContract".equals(msgtype)|| "Tl_AfterRenting".equals(msgtype)){
msgcontent = msgcontent.replace("@", "=");
}
//获取是否按日期去重
String isrepatebydate = data.getString("isrepeatbydate");
//获取短信替换参数
int oldlength = msgcontent.length();
int newlength = msgcontent.replace("}", "").length();
String[] params = new String[oldlength-newlength];
if(params.length>0){
int index = 0;
for(int i=0;i<params.length;i++){
int start = msgcontent.indexOf("{", index);
int end = msgcontent.indexOf("}", index);
params[i] = msgcontent.substring(start+1, end);
index = end+1;
}
}
JBOFactory.getBizObjectManager(MSG_CONFIG.CLASS_NAME,tx).createQuery("update O set previous_fire_time='"+DateUtil.getDateTime(trigger.getPreviousFireTime())+"',next_fire_time='"+DateUtil.getDateTime(trigger.getNextFireTime())+"' where id='"+id+"'");
ASResultSet result = tran.getASResultSet(new SqlObject(msgsql));
while(result.next()){
boolean flag = false;
for(int p=0;p<params.length;p++){
if(result.getString(params[p]) == null){
flag = true;
}
}
if(flag){
continue;
}
String resultMsgContent = msgcontent;
Object phonenumber = result.getString("phonenumber");
if(phonenumber == null || phonenumber.toString().length() != 11){
continue;
}
String sql = "select * from msg_send_relative where 1=1 ";
String[] sqlparams = msgsqlparam.split("&");
if(sqlparams.length>0){
for(int i=0;i<sqlparams.length;i++){
sql += "and "+sqlparams[i]+"='"+result.getString(sqlparams[i]).toString()+"' ";
}
}
if(isrepatebydate.equals("yes")){//根据日期去重
sql+= "and inputtime='"+result.getString("checkdate")+"'";
}
if(msgtype.startsWith("holiday") || msgtype.startsWith("birthday")){//如果是生日祝福和节假日祝福必须添加短信类型和日期条件筛选
sql += "and msg_type='"+msgtype+"' and inputtime='"+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+"'";
}else{
sql += "and msg_type='"+msgtype+"'";
}
sql = sql.replaceAll(":", "");
SqlObject so = new SqlObject(sql);
so.setRunSql(so.getRunSql().replaceAll("", ":"));
ASResultSet msgSend = tran.getASResultSet(so);
if(!msgSend.next()){
for(int i=0;i<params.length;i++){
resultMsgContent = resultMsgContent.replace(params[i], result.getString(params[i]));
}
resultMsgContent = resultMsgContent.replace("{", "");
resultMsgContent = resultMsgContent.replace("}", "");
//创建短信发送记录
BizObjectManager bomLSNT = JBOFactory.getBizObjectManager(LB_SMS_NOTICE_TASKS.CLASS_NAME,tx);
BizObject sn = bomLSNT.newObject();
sn.setAttributeValue("inputuserid", result.getString("proj_manage")!=null?result.getString("proj_manage"):data.getString("userID"));
sn.setAttributeValue("customer_id", result.getString("customer_id"));
sn.setAttributeValue("phone_number", phonenumber.toString());
//sn.setAttributeValue("phone_number", "13718374615");
sn.setAttributeValue("send_flag", 0);
sn.setAttributeValue("sms_content", resultMsgContent);
sn.setAttributeValue("sms_type", "DELAYED");
sn.setAttributeValue("inputtime", DateUtil.getDateTime(new Date()));
bomLSNT.saveObject(sn);
//关联表生成记录
String insertSql = "insert into msg_send_relative (id,sms_id,msg_type,column) values('"+UUIDUtil.getUUID()+"','"+sn.getAttribute("ID").getString()+"','"+msgtype+"',data)";
String column = "";
String value = "";
for(int m=0;m<sqlparams.length;m++){
column += ","+sqlparams[m];
value += ",'"+result.getString(sqlparams[m]).toString()+"'";
}
column = column.substring(1, column.length());
value = value.substring(1,value.length());
if(msgtype.startsWith("holiday") || msgtype.startsWith("birthday")){
column += ",inputtime";
value += ",'"+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+"'";
}
if(isrepatebydate.equals("yes")){//根据日期去重
column += ",inputtime";
value += ",'"+result.getString("checkdate")+"'";
}
if("trigger_mode02".equals(triggermode)){//手动触发,不需要定时代理
continue;
}
//拼接短信发送定时代理
String jobName = UUIDUtil.getUUID();
String triggerName = UUIDUtil.getUUID();
Map<String,Object> dataMap = new HashMap<String,Object>();
dataMap.put("smsnoticeid", sn.getAttribute("ID").getString());
Class jobClass = Class.forName("com.tenwa.message.JobSendMessage");
JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, MSG_GROUP_NAME)
.usingJobData(new JobDataMap(dataMap)).requestRecovery("1".equals(isoverdateexecute)?true:false).storeDurably(false).build();
Date startTime = DateUtil.getTimeByFormat(DateUtil.getDateTime(new Date()), "yyyy-MM-dd HH:mm:ss");
//动态创建时间表达式
String cron = "";
Calendar ca = Calendar.getInstance();
ca.setTime(new Date());
if(timeSet != null){
if(timeSet.compareTo(timeNow) <= 0){
checkTime = true;
}
cron += msgsendtime.split(":")[2]+" ";
cron += msgsendtime.split(":")[1]+" ";
cron += msgsendtime.split(":")[0]+" ";
if(checkTime){
cron = "";
String tNow = new SimpleDateFormat("HH:mm:ss").format(new Date(new Date().getTime()+2000));
cron += tNow.split(":")[2]+" ";
cron += tNow.split(":")[1]+" ";
cron += tNow.split(":")[0]+" ";
}
}
CronExpression ce = null;
column += ",msg_send_jobname,msg_send_triggername";
value += ",'"+jobName+"','"+triggerName+"'";
insertSql = insertSql.replace("column", column);
insertSql = insertSql.replace("data", value);
insertSql = insertSql.replaceAll(":", "");
SqlObject soInsert = new SqlObject(insertSql);
soInsert.setRunSql(soInsert.getRunSql().replaceAll("", ":"));
tran.executeSQL(new SqlObject(insertSql));
switch(msgsendtype){
case "msg_time_type01"://当天立即
cron = "";
String tNow = new SimpleDateFormat("HH:mm:ss").format(new Date(new Date().getTime()+2000));
cron += tNow.split(":")[2]+" ";
cron += tNow.split(":")[1]+" ";
cron += tNow.split(":")[0]+" ";
cron += ca.get(Calendar.DAY_OF_MONTH)+" ";
cron += (ca.get(Calendar.MONTH)+1)+" ? *";
ce = new CronExpression(cron);
trigger = TriggerBuilder.newTrigger().forJob(jobName, MSG_GROUP_NAME).withIdentity(triggerName, MSG_GROUP_NAME).startAt(startTime).endAt(new Date(new Date().getTime()+(24*60*60*1000)))
.withSchedule(CronScheduleBuilder.cronSchedule(ce).withMisfireHandlingInstructionDoNothing())
.build();
getScheduler().scheduleJob(jobDetail,trigger);
sn.setAttributeValue("sms_type", "IMMEDIATELY");
break;
case "msg_time_type02"://当天指定时间
cron += ca.get(Calendar.DAY_OF_MONTH)+" ";
cron += (ca.get(Calendar.MONTH)+1)+" ? *";
ce = new CronExpression(cron);
trigger = TriggerBuilder.newTrigger().forJob(jobName, MSG_GROUP_NAME).withIdentity(triggerName, MSG_GROUP_NAME).startAt(startTime).endAt(new Date(new Date().getTime()+(24*60*60*1000)))
.withSchedule(CronScheduleBuilder.cronSchedule(ce).withMisfireHandlingInstructionDoNothing())
.build();
getScheduler().scheduleJob(jobDetail,trigger);
break;
case "msg_time_type03"://本周最后一天
cron += ca.getActualMaximum(Calendar.DAY_OF_WEEK_IN_MONTH)+" ";
cron += (ca.get(Calendar.MONTH)+1)+" ? *";
ce = new CronExpression(cron);
trigger = TriggerBuilder.newTrigger().forJob(jobName, MSG_GROUP_NAME).withIdentity(triggerName, MSG_GROUP_NAME).startAt(startTime).endAt(new Date(new Date().getTime()+(8*24*60*60*1000)))
.withSchedule(CronScheduleBuilder.cronSchedule(ce).withMisfireHandlingInstructionDoNothing())
.build();
getScheduler().scheduleJob(jobDetail,trigger);
break;
case "msg_time_type04"://本月最后一天
cron += ca.getActualMaximum(Calendar.DAY_OF_MONTH)+" ";
cron += (ca.get(Calendar.MONTH)+1)+" ? *";
ce = new CronExpression(cron);
trigger = TriggerBuilder.newTrigger().forJob(jobName, MSG_GROUP_NAME).withIdentity(triggerName, MSG_GROUP_NAME).startAt(startTime).endAt(new Date(new Date().getTime()+(31*24*60*60*1000)))
.withSchedule(CronScheduleBuilder.cronSchedule(ce).withMisfireHandlingInstructionDoNothing())
.build();
getScheduler().scheduleJob(jobDetail,trigger);
break;
case "msg_time_type05"://延迟天
cron += (ca.get(Calendar.DAY_OF_MONTH)+Integer.parseInt(delayday))+" ";
cron += (ca.get(Calendar.MONTH)+1)+" ? *";
ce = new CronExpression(cron);
trigger = TriggerBuilder.newTrigger().forJob(jobName, MSG_GROUP_NAME).withIdentity(triggerName, MSG_GROUP_NAME).startAt(startTime).endAt(new Date(new Date().getTime()+(Integer.parseInt(delayday)*24*60*60*1000)))
.withSchedule(CronScheduleBuilder.cronSchedule(ce).withMisfireHandlingInstructionDoNothing())
.build();
getScheduler().scheduleJob(jobDetail,trigger);
break;
}
sn.setAttributeValue("notice_time", DateUtil.getDateTime(ce.getNextValidTimeAfter(startTime)));
ListenerManager lm = sch.getListenerManager();
KeyMatcher<JobKey> keyMetcher = KeyMatcher.keyEquals(JobKey.jobKey(jobName, MSG_GROUP_NAME));
lm.addJobListener(new JobListenerImpl(), keyMetcher);
bomLSNT.saveObject(sn);
}
}
tx.commit();
} catch (Exception e) {
e.printStackTrace();
try {
tx.rollback();
} catch (JBOException e1) {
e1.printStackTrace();
}
}
}
public Scheduler getScheduler() throws Exception
{
return StdSchedulerFactory.getDefaultScheduler();
}
//关联记录不存在,新建短信任务,发送短信通知
if (!msgSend.next()) {
for (int i = 0; i < params.length; i++) {
rsMsgContent = rsMsgContent.replace(params[i], rs.getString(params[i]));
}
rsMsgContent = rsMsgContent.replace("{", "");
rsMsgContent = rsMsgContent.replace("}", "");
//创建短信发送记录
BizObjectManager bomLSNT = JBOFactory.getBizObjectManager(LB_SMS_NOTICE_TASKS.CLASS_NAME, inner_tx);
BizObject sn = bomLSNT.newObject();
sn.setAttributeValue("inputuserid", rs.getString("proj_manage") != null ? rs.getString("proj_manage") : data.getString("userID"));
sn.setAttributeValue("customer_id", rs.getString("customer_id"));
sn.setAttributeValue("phone_number", phonenumber.toString());
sn.setAttributeValue("send_flag", 0);
sn.setAttributeValue("sms_content", rsMsgContent);
sn.setAttributeValue("sms_type", "DELAYED");
sn.setAttributeValue("inputtime", DateUtil.getDateTime(new Date()));
bomLSNT.saveObject(sn);
if ("trigger_mode02".equals(triggermode)) {//手动触发,不需要定时代理
continue;
}
//关联表生成记录
String insertSql = "insert into msg_send_relative (id,sms_id,msg_type,column) values('" + UUIDUtil.getUUID() + "','" + sn.getAttribute("ID").getString() + "','" + msgtype + "',data)";
String column = "";
String value = "";
for (int m = 0; m < sqlparams.length; m++) {
column += "," + sqlparams[m];
value += ",'" + rs.getString(sqlparams[m]).toString() + "'";
}
column = column.substring(1, column.length());
value = value.substring(1, value.length());
if (msgtype.startsWith("holiday") || msgtype.startsWith("birthday")) {
column += ",inputtime";
value += ",'" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "'";
}
if (isrepatebydate.equals("yes")) {//根据日期去重
column += ",inputtime";
value += ",'" + rs.getString("checkdate") + "'";
}
String jobName = UUIDUtil.getUUID();
String triggerName = UUIDUtil.getUUID();
//记录短信发送定时代理
column += ",msg_send_jobname,msg_send_triggername";
value += ",'" + jobName + "','" + triggerName + "'";
insertSql = insertSql.replace("column", column);
insertSql = insertSql.replace("data", value);
insertSql = insertSql.replaceAll(":", "");
SqlObject soInsert = new SqlObject(insertSql);
soInsert.setRunSql(soInsert.getRunSql().replaceAll("", ":"));
inner_tran.executeSQL(new SqlObject(insertSql));
Date startTime = DateUtil.getTimeByFormat(DateUtil.getDateTime(new Date()), "yyyy-MM-dd HH:mm:ss");
//动态创建时间表达式
String cron = "";
Calendar ca = Calendar.getInstance();
ca.setTime(new Date());
if (timeSet != null) {
if (timeSet.compareTo(timeNow) <= 0) {
checkTime = true;
}
cron += msgsendtime.split(":")[2] + " ";
cron += msgsendtime.split(":")[1] + " ";
cron += msgsendtime.split(":")[0] + " ";
if (checkTime) {
cron = "";
String tNow = new SimpleDateFormat("HH:mm:ss").format(new Date(new Date().getTime() + 2000));
cron += tNow.split(":")[2] + " ";
cron += tNow.split(":")[1] + " ";
cron += tNow.split(":")[0] + " ";
}
}
//定时任务处理
Map<String, Object> dataMap = new HashMap<String, Object>();
dataMap.put("smsnoticeid", sn.getAttribute("ID").getString());
JobDetail jobDetail = JobBuilder.newJob(JobSendMessage.class).withIdentity(jobName, MSG_GROUP_NAME)
.usingJobData(new JobDataMap(dataMap)).requestRecovery("1".equals(isoverdateexecute) ? true : false).storeDurably(false).build();
CronExpression ce = null;
switch (msgsendtype) {
case "msg_time_type01"://当天立即
cron = "";
String tNow = new SimpleDateFormat("HH:mm:ss").format(new Date(new Date().getTime() + 2000));
cron += tNow.split(":")[2] + " ";
cron += tNow.split(":")[1] + " ";
cron += tNow.split(":")[0] + " ";
cron += ca.get(Calendar.DAY_OF_MONTH) + " ";
cron += (ca.get(Calendar.MONTH) + 1) + " ? *";
ce = new CronExpression(cron);
trigger = TriggerBuilder.newTrigger().forJob(jobName, MSG_GROUP_NAME).withIdentity(triggerName, MSG_GROUP_NAME).startAt(startTime).endAt(new Date(new Date().getTime() + (24 * 60 * 60 * 1000)))
.withSchedule(CronScheduleBuilder.cronSchedule(ce).withMisfireHandlingInstructionDoNothing())
.build();
sn.setAttributeValue("sms_type", "IMMEDIATELY");
ARE.getLog().warn(triggerName + " cron : " + cron);
break;
case "msg_time_type02"://当天指定时间
cron += ca.get(Calendar.DAY_OF_MONTH) + " ";
cron += (ca.get(Calendar.MONTH) + 1) + " ? *";
ce = new CronExpression(cron);
trigger = TriggerBuilder.newTrigger().forJob(jobName, MSG_GROUP_NAME).withIdentity(triggerName, MSG_GROUP_NAME).startAt(startTime).endAt(new Date(new Date().getTime() + (24 * 60 * 60 * 1000)))
.withSchedule(CronScheduleBuilder.cronSchedule(ce).withMisfireHandlingInstructionDoNothing())
.build();
break;
case "msg_time_type03"://本周最后一天
cron += ca.getActualMaximum(Calendar.DAY_OF_WEEK_IN_MONTH) + " ";
cron += (ca.get(Calendar.MONTH) + 1) + " ? *";
ce = new CronExpression(cron);
trigger = TriggerBuilder.newTrigger().forJob(jobName, MSG_GROUP_NAME).withIdentity(triggerName, MSG_GROUP_NAME).startAt(startTime).endAt(new Date(new Date().getTime() + (8 * 24 * 60 * 60 * 1000)))
.withSchedule(CronScheduleBuilder.cronSchedule(ce).withMisfireHandlingInstructionDoNothing())
.build();
break;
case "msg_time_type04"://本月最后一天
cron += ca.getActualMaximum(Calendar.DAY_OF_MONTH) + " ";
cron += (ca.get(Calendar.MONTH) + 1) + " ? *";
ce = new CronExpression(cron);
trigger = TriggerBuilder.newTrigger().forJob(jobName, MSG_GROUP_NAME).withIdentity(triggerName, MSG_GROUP_NAME).startAt(startTime).endAt(new Date(new Date().getTime() + (31 * 24 * 60 * 60 * 1000)))
.withSchedule(CronScheduleBuilder.cronSchedule(ce).withMisfireHandlingInstructionDoNothing())
.build();
break;
case "msg_time_type05"://延迟天
cron += (ca.get(Calendar.DAY_OF_MONTH) + Integer.parseInt(delayday)) + " ";
cron += (ca.get(Calendar.MONTH) + 1) + " ? *";
ce = new CronExpression(cron);
trigger = TriggerBuilder.newTrigger().forJob(jobName, MSG_GROUP_NAME).withIdentity(triggerName, MSG_GROUP_NAME).startAt(startTime).endAt(new Date(new Date().getTime() + (Integer.parseInt(delayday) * 24 * 60 * 60 * 1000)))
.withSchedule(CronScheduleBuilder.cronSchedule(ce).withMisfireHandlingInstructionDoNothing())
.build();
break;
}
sn.setAttributeValue("notice_time", DateUtil.getDateTime(ce.getNextValidTimeAfter(startTime)));
bomLSNT.saveObject(sn);
scheduler.scheduleJob(jobDetail, trigger);
}
inner_tran.commit();
}
tran.commit();
} catch (Exception e) {
e.printStackTrace();
try {
if (tx != null) tx.rollback();
if (inner_tx != null) inner_tx.rollback();
} catch (JBOException e1) {
e1.printStackTrace();
}
}
}
public Scheduler getScheduler() throws Exception {
return StdSchedulerFactory.getDefaultScheduler();
}
}