定时任务 完成

表达式   完成
邮件工具类
yun-zuoyi
yunhao.wang 7 years ago
parent 59806414b9
commit ec137693cf

@ -4,6 +4,7 @@ import cn.estsh.i3plus.pojo.base.bean.ListPager;
import cn.estsh.i3plus.pojo.base.common.Pager; import cn.estsh.i3plus.pojo.base.common.Pager;
import cn.estsh.i3plus.pojo.platform.bean.SessionUser; import cn.estsh.i3plus.pojo.platform.bean.SessionUser;
import cn.estsh.i3plus.pojo.platform.bean.TaskTime; import cn.estsh.i3plus.pojo.platform.bean.TaskTime;
import cn.estsh.i3plus.pojo.platform.bean.TaskTimeExpression;
import java.util.List; import java.util.List;
@ -17,10 +18,17 @@ import java.util.List;
public interface ITaskTimeService { public interface ITaskTimeService {
/** /**
*
* @param taskTime
* @return
*/
TaskTime insertTaskTime(TaskTime taskTime, TaskTimeExpression taskTimeExpression);
/**
* *
* @param taskTime * @param taskTime
*/ */
void updateTaskTime(TaskTime taskTime); void updateTaskTime(TaskTime taskTime, TaskTimeExpression taskTimeExpression);
/** /**
* *
@ -37,13 +45,6 @@ public interface ITaskTimeService {
void deleteTaskTimeById(String id); void deleteTaskTimeById(String id);
/** /**
*
* @param taskTime
* @return
*/
TaskTime insertTaskTime(TaskTime taskTime);
/**
* *
* @return * @return
*/ */
@ -76,4 +77,18 @@ public interface ITaskTimeService {
* *
*/ */
void updateTaskTimeStatusByIds(String[] ids, Integer status); void updateTaskTimeStatusByIds(String[] ids, Integer status);
/**
*
* @param lastDate
* @param name
* @param groupName
*/
void doTaskTimeLastDateByNameAndGroupName(String lastDate,String name,String groupName);
/**
*
* @param idStr
*/
void executeTaskTimeById(long idStr);
} }

@ -112,6 +112,11 @@
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<!-- JavaMail -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</dependency>
</dependencies> </dependencies>
<build> <build>

@ -39,7 +39,7 @@ public class DemoScheduleController {
System.out.println(ti); System.out.println(ti);
} }
return new ResultBean(true,""); return new ResultBean(true,"").setResultList(taskList);
} }
@GetMapping(value="/add-task") @GetMapping(value="/add-task")

@ -46,28 +46,33 @@ public class TaskTimeController {
@PostMapping(value = "/insert") @PostMapping(value = "/insert")
@ApiOperation(value = "新增定时任务", notes = "定时任务") @ApiOperation(value = "新增定时任务", notes = "定时任务")
public ResultBean insertTaskTime(TaskTime taskTime) { public ResultBean insertTaskTime(TaskTime taskTime,Boolean isExecute) {
try { try {
// 数据校验 // 数据校验
ValidatorBean.beginValid(taskTime) ValidatorBean.beginValid(taskTime)
.notNull("timeId", taskTime.getTimeId())
.notNull("name", taskTime.getName()) .notNull("name", taskTime.getName())
.notNull("timeId",taskTime.getTimeId()) .notNull("groupName",taskTime.getGroupName())
.notNull("taskMethodTypeId", taskTime.getTaskMethodTypeId()); .notNull("timeExpressionId",taskTime.getTimeExpressionId())
.notNull("taskMethodTypeId", taskTime.getTaskMethodTypeId())
.notNull("taskPackage",taskTime.getTaskPackage())
.notNull("taskClass",taskTime.getTaskClass());
TaskTimeExpression taskTimeExpression = taskTimeExpressionService.getTaskTimeExpressionById(taskTime.getTimeId().toString()); TaskTimeExpression taskTimeExpression = taskTimeExpressionService
ValidatorBean.beginValid(taskTimeExpression); .getTaskTimeExpressionById(taskTime.getTimeExpressionId().toString());
ValidatorBean.checkNotNull(taskTimeExpression,"定时执行策略不存在");
taskTime.setRedTimeName(taskTimeExpression.getName()); taskTime.setTimeExpressionNameRdd(taskTimeExpression.getName());
taskTime.setRedTimeExpression(taskTimeExpression.getExpressionContent()); taskTime.setTimeExpressionContentRdd(taskTimeExpression.getExpressionContent());
taskTime.setTaskStartDateTimeRdd(taskTimeExpression.getExpressionStartDatetime());
taskTime.setTaskEndDateTimeRdd(taskTimeExpression.getExpressionEndDatetime());
taskTime.setTaskStatus(CommonEnumUtil.DATA_STATUS.ENABLE.getValue()); taskTime.setTaskStatus(CommonEnumUtil.DATA_STATUS.ENABLE.getValue());
ConvertBean.modelInitialize(taskTime, AuthUtil.getSessionUser()); taskTime = taskTimeService.insertTaskTime(taskTime,taskTimeExpression);
// 立即执行
taskTime = taskTimeService.insertTaskTime(taskTime); if(isExecute != null && isExecute){
return ResultBean.success("操作成功") taskTimeService.executeTaskTimeById(taskTime.getId());
.setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()) }
.setResultObject(taskTime); return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultObject(taskTime);
} catch (ImppBusiException busExcep) { } catch (ImppBusiException busExcep) {
LOGGER.error(busExcep.getErrorMsg() + "{}", busExcep.getErrorDetail(), busExcep); LOGGER.error(busExcep.getErrorMsg() + "{}", busExcep.getErrorDetail(), busExcep);
return ResultBean.fail(busExcep.getErrorShow()); return ResultBean.fail(busExcep.getErrorShow());
@ -79,31 +84,33 @@ public class TaskTimeController {
@PutMapping(value = "/update") @PutMapping(value = "/update")
@ApiOperation(value = "修改定时任务", notes = "定时任务") @ApiOperation(value = "修改定时任务", notes = "定时任务")
public ResultBean updateTaskTime(TaskTime taskTime) { public ResultBean updateTaskTime(TaskTime taskTime,Boolean isExecute) {
try { try {
// 数据校验 // 数据校验
ValidatorBean.beginValid(taskTime) ValidatorBean.beginValid(taskTime)
.notNull("id", taskTime.getId()) .notNull("id", taskTime.getId())
.notNull("timeId", taskTime.getTimeId())
.notNull("name", taskTime.getName()) .notNull("name", taskTime.getName())
.notNull("taskMethodTypeId",taskTime.getTaskMethodTypeId()); .notNull("groupName",taskTime.getGroupName())
.notNull("timeExpressionId",taskTime.getTimeExpressionId())
TaskTimeExpression taskTimeExpression = taskTimeExpressionService.getTaskTimeExpressionById(taskTime.getTimeId().toString()); .notNull("taskMethodTypeId", taskTime.getTaskMethodTypeId())
.notNull("taskPackage",taskTime.getTaskPackage())
// 数据真实性校验 .notNull("taskClass",taskTime.getTaskClass());
ValidatorBean.beginValid(taskTimeExpression);
// 数据冗余 TaskTimeExpression taskTimeExpression = taskTimeExpressionService
taskTime.setRedTimeName(taskTimeExpression.getName()); .getTaskTimeExpressionById(taskTime.getTimeExpressionId().toString());
taskTime.setRedTimeExpression(taskTimeExpression.getExpressionContent()); ValidatorBean.checkNotNull(taskTimeExpression,"定时执行策略不存在");
ConvertBean.modelUpdate(taskTime, AuthUtil.getSessionUser()); taskTime.setTimeExpressionNameRdd(taskTimeExpression.getName());
taskTime.setTimeExpressionContentRdd(taskTimeExpression.getExpressionContent());
taskTimeService.updateTaskTime(taskTime); taskTime.setTaskStartDateTimeRdd(taskTimeExpression.getExpressionStartDatetime());
taskTime.setTaskEndDateTimeRdd(taskTimeExpression.getExpressionEndDatetime());
taskTime.setTaskStatus(CommonEnumUtil.DATA_STATUS.ENABLE.getValue());
return ResultBean.success("操作成功") taskTimeService.updateTaskTime(taskTime,taskTimeExpression);
.setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()) if(isExecute != null && isExecute){
.setResultObject(taskTime); taskTimeService.executeTaskTimeById(taskTime.getId());
}
return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultObject(taskTime);
} catch (ImppBusiException busExcep) { } catch (ImppBusiException busExcep) {
LOGGER.error(busExcep.getErrorMsg() + "{}", busExcep.getErrorDetail(), busExcep); LOGGER.error(busExcep.getErrorMsg() + "{}", busExcep.getErrorDetail(), busExcep);
return ResultBean.fail(busExcep.getErrorShow()); return ResultBean.fail(busExcep.getErrorShow());
@ -250,4 +257,22 @@ public class TaskTimeController {
return ResultBean.fail().setCode(ImppExceptionEnum.BUSINESS_EXCEPTION_DATA_ERROR.getCode()); return ResultBean.fail().setCode(ImppExceptionEnum.BUSINESS_EXCEPTION_DATA_ERROR.getCode());
} }
} }
@GetMapping(value = "/execute/{id}")
@ApiOperation(value = "立即执行", notes = "立即执行")
public ResultBean executeByTaskTimeId(@PathVariable("id") String id) {
try {
// 数据校验
ValidatorBean.checkNotNull(id, "定时任务id 不能为空");
taskTimeService.executeTaskTimeById(Long.parseLong(id));
return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
} catch (ImppBusiException busExcep) {
LOGGER.error(busExcep.getErrorMsg() + "{}", busExcep.getErrorDetail(), busExcep);
return ResultBean.fail(busExcep.getErrorShow());
} catch (Exception e) {
LOGGER.error(ImppExceptionEnum.SYSTEM_EXCEPTION.getDescription() + "{}", e.getMessage(), e);
return ResultBean.fail().setCode(ImppExceptionEnum.SYSTEM_EXCEPTION.getCode());
}
}
} }

@ -1,11 +1,19 @@
package cn.estsh.i3plus.core.apiservice.schedulejob; package cn.estsh.i3plus.core.apiservice.schedulejob;
import cn.estsh.i3plus.core.api.iservice.busi.ITaskTimeService;
import cn.estsh.i3plus.pojo.platform.repository.TaskTimeRepository;
import cn.estsh.impp.framework.base.schedule.BaseImppScheduleJob; import cn.estsh.impp.framework.base.schedule.BaseImppScheduleJob;
import cn.estsh.impp.framework.boot.init.ApplicationProperties; import cn.estsh.impp.framework.boot.init.ApplicationProperties;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import org.quartz.JobExecutionContext; import org.quartz.JobExecutionContext;
import org.quartz.Scheduler;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.text.SimpleDateFormat;
import java.util.Date;
/** /**
* @Description : * @Description :
@ -18,12 +26,21 @@ import org.slf4j.LoggerFactory;
public class DemoJob extends BaseImppScheduleJob { public class DemoJob extends BaseImppScheduleJob {
public static final Logger LOGGER = LoggerFactory.getLogger(DemoJob.class); public static final Logger LOGGER = LoggerFactory.getLogger(DemoJob.class);
@Autowired
private ITaskTimeService taskTimeService;
public DemoJob() { public DemoJob() {
super(DemoJob.class,"定时任务demo"); super(DemoJob.class,"定时任务demo");
} }
@Override @Override
public void executeImppJob(JobExecutionContext context, ApplicationProperties applicationProperties) { public void executeImppJob(JobExecutionContext context, ApplicationProperties applicationProperties) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:dd");
taskTimeService.doTaskTimeLastDateByNameAndGroupName(sdf.format(new Date()),
context.getJobDetail().getKey().getName(),
context.getJobDetail().getKey().getGroup());
System.out.println("定时任务被执行");
LOGGER.info("projectName{},port:{}",applicationProperties.getApplicationName(),applicationProperties.getServerPort()); LOGGER.info("projectName{},port:{}",applicationProperties.getApplicationName(),applicationProperties.getServerPort());
} }
} }

@ -12,11 +12,14 @@ import cn.estsh.i3plus.pojo.platform.repository.TaskTimeRepository;
import cn.estsh.i3plus.pojo.platform.sqlpack.CoreHqlPack; import cn.estsh.i3plus.pojo.platform.sqlpack.CoreHqlPack;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder; import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import cn.estsh.impp.framework.boot.exception.ImppExceptionEnum; import cn.estsh.impp.framework.boot.exception.ImppExceptionEnum;
import org.quartz.*;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List; import java.util.List;
/** /**
@ -51,6 +54,8 @@ public class TaskTimeExpressionServiceImpl implements ITaskTimeExpressionService
@Override @Override
public TaskTimeExpression insertTaskTimeExpression(TaskTimeExpression taskTimeExpression) { public TaskTimeExpression insertTaskTimeExpression(TaskTimeExpression taskTimeExpression) {
LOGGER.info("定时任务时间表达式 TASK_TIME_EXPRESSION :{}", taskTimeExpression); LOGGER.info("定时任务时间表达式 TASK_TIME_EXPRESSION :{}", taskTimeExpression);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return taskTimeExpressionRDao.insert(taskTimeExpression); return taskTimeExpressionRDao.insert(taskTimeExpression);
} }

@ -4,16 +4,30 @@ import cn.estsh.i3plus.core.api.iservice.busi.ITaskTimeService;
import cn.estsh.i3plus.pojo.base.bean.ListPager; import cn.estsh.i3plus.pojo.base.bean.ListPager;
import cn.estsh.i3plus.pojo.base.common.Pager; import cn.estsh.i3plus.pojo.base.common.Pager;
import cn.estsh.i3plus.pojo.base.common.PagerHelper; import cn.estsh.i3plus.pojo.base.common.PagerHelper;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.ImppEnumUtil;
import cn.estsh.i3plus.pojo.base.tool.HqlPack; import cn.estsh.i3plus.pojo.base.tool.HqlPack;
import cn.estsh.i3plus.pojo.platform.bean.RefExpressionTrigger;
import cn.estsh.i3plus.pojo.platform.bean.SessionUser; import cn.estsh.i3plus.pojo.platform.bean.SessionUser;
import cn.estsh.i3plus.pojo.platform.bean.TaskTime; import cn.estsh.i3plus.pojo.platform.bean.TaskTime;
import cn.estsh.i3plus.pojo.platform.bean.TaskTimeExpression;
import cn.estsh.i3plus.pojo.platform.repository.RefExpressionTriggerRepository;
import cn.estsh.i3plus.pojo.platform.repository.TaskTimeRepository; import cn.estsh.i3plus.pojo.platform.repository.TaskTimeRepository;
import cn.estsh.i3plus.pojo.platform.sqlpack.CoreHqlPack; import cn.estsh.i3plus.pojo.platform.sqlpack.CoreHqlPack;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import cn.estsh.impp.framework.boot.exception.ImppExceptionEnum;
import cn.estsh.impp.framework.boot.util.ValidatorBean;
import org.hibernate.service.spi.ServiceException;
import org.quartz.*;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List; import java.util.List;
/** /**
@ -30,11 +44,65 @@ public class TaskTimeServiceImpl implements ITaskTimeService {
@Autowired @Autowired
private TaskTimeRepository taskTimeRDao; private TaskTimeRepository taskTimeRDao;
@Autowired
private RefExpressionTriggerRepository refExpressionTriggerRDao;
@Autowired
private Scheduler scheduler;
@Override @Override
public void updateTaskTime(TaskTime taskTime) { public void updateTaskTime(TaskTime taskTime, TaskTimeExpression taskTimeExpression) {
LOGGER.info("定时任务 TASK_TIME :{}", taskTime); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
TaskTime oldTaskTime = taskTimeRDao.getById(taskTime.getId());
// 更新关系表
refExpressionTriggerRDao.updateByProperties(
"expressionId",oldTaskTime.getTimeExpressionId(),
new String[]{"name","groupName"},
new String[]{oldTaskTime.getName(),taskTime.getGroupName()}
);
taskTimeRDao.update(taskTime); taskTimeRDao.update(taskTime);
try {
TriggerKey triggerKey = TriggerKey.triggerKey(taskTime.getName(),taskTime.getGroupName());
System.out.println(scheduler.getTrigger(triggerKey));
if (!scheduler.checkExists(triggerKey)) {
throw ImppExceptionBuilder.newInstance()
.setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
.setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
.setErrorDetail("定时任务不存在")
.setErrorSolution("请重新选择")
.build();
}
// 添加定时任务与触发器到quartz表中
CronScheduleBuilder schedBuilder = CronScheduleBuilder
.cronSchedule(taskTimeExpression.getExpressionContent())
.withMisfireHandlingInstructionDoNothing();
TriggerBuilder<CronTrigger> trigger = TriggerBuilder.newTrigger()
.withIdentity(triggerKey)
.withDescription(taskTimeExpression.getExpressionDescription())
.withSchedule(schedBuilder)
.startAt(sdf.parse(taskTimeExpression.getExpressionStartDatetime()));
if(taskTimeExpression.getExpressionEndDatetime() != null){
trigger = trigger.endAt(sdf.parse(taskTimeExpression.getExpressionEndDatetime()));
}
JobKey jobKey = new JobKey(taskTime.getName(), taskTime.getGroupName());
JobDetail jobDetail = scheduler.getJobDetail(jobKey);
jobDetail.getJobBuilder().withDescription(taskTime.getTaskDescription());
HashSet<Trigger> triggerSet = new HashSet<>();
triggerSet.add(trigger.build());
scheduler.scheduleJob(jobDetail, triggerSet, true);
} catch (SchedulerException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
} }
@Override @Override
@ -44,18 +112,117 @@ public class TaskTimeServiceImpl implements ITaskTimeService {
taskTime.setTaskStatus(status); taskTime.setTaskStatus(status);
taskTime.setModifyUser(user.getUserName()); taskTime.setModifyUser(user.getUserName());
taskTimeRDao.update(taskTime); taskTimeRDao.update(taskTime);
try {
TriggerKey triggerKey = TriggerKey.triggerKey(taskTime.getName(), taskTime.getGroupName());
if (!scheduler.checkExists(triggerKey)) {
}
if (status == CommonEnumUtil.DATA_STATUS.ENABLE.getValue()){
scheduler.resumeTrigger(triggerKey);
} else {
scheduler.pauseTrigger(triggerKey);
}
} catch (SchedulerException e) {
LOGGER.info("重新开始任务-->复杂调度" + e.getMessage());
e.printStackTrace();
}
} }
@Override @Override
public void deleteTaskTimeById(String id) { public void deleteTaskTimeById(String id) {
LOGGER.info("定时任务 TASK_TIME Key:{}", id); try {
taskTimeRDao.deleteById(Long.parseLong(id)); TaskTime taskTime = taskTimeRDao.getById(Long.parseLong(id));
ValidatorBean.checkNotNull(taskTime,"定时任务不存在");
taskTimeRDao.deleteById(Long.parseLong(id));
// 删除关系表数据
refExpressionTriggerRDao.deleteByProperty("expressionId",taskTime.getTimeExpressionId());
TriggerKey triggerKey = TriggerKey.triggerKey(taskTime.getName(),taskTime.getGroupName());
if(scheduler.checkExists(triggerKey)){
scheduler.pauseTrigger(triggerKey);
scheduler.unscheduleJob(triggerKey);
}else {
throw ImppExceptionBuilder.newInstance()
.setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
.setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
.setErrorDetail("定时任务不存在")
.setErrorSolution("请重新选择")
.build();
}
} catch (SchedulerException e) {
throw ImppExceptionBuilder.newInstance()
.setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
.setErrorCode(ImppExceptionEnum.TASK_EXCEPTION.getCode())
.build();
}
} }
@Override @Override
public TaskTime insertTaskTime(TaskTime taskTime) { public TaskTime insertTaskTime(TaskTime taskTime, TaskTimeExpression taskTimeExpression) {
LOGGER.info("定时任务 TASK_TIME :{}", taskTime); try {
return taskTimeRDao.insert(taskTime); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 唯一校验
JobKey jobKey = JobKey.jobKey(taskTime.getName(),taskTime.getGroupName());
TriggerKey triggerKey = TriggerKey.triggerKey(taskTime.getName(),taskTime.getGroupName());
if (taskTimeRDao.isExitByProperty(new String[]{"name","groupName"},new String[]{taskTime.getName(),taskTime.getGroupName()})
|| scheduler.checkExists(jobKey) || scheduler.checkExists(triggerKey)){
throw ImppExceptionBuilder.newInstance()
.setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
.setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
.setErrorDetail("定时任务已存在")
.setErrorSolution("请重新输入任务名称和组名称")
.build();
}
RefExpressionTrigger refExpressionTrigger = new RefExpressionTrigger();
refExpressionTrigger.setExpressionId(taskTimeExpression.getId());
refExpressionTrigger.setTriggerName(taskTime.getName());
refExpressionTrigger.setTriggerGroupName(taskTime.getGroupName());
taskTime = taskTimeRDao.insert(taskTime);
// 添加表达式与触发器关系表
refExpressionTriggerRDao.insert(refExpressionTrigger);
// 添加定时任务与触发器到quartz表中
CronScheduleBuilder schedBuilder = CronScheduleBuilder
.cronSchedule(taskTimeExpression.getExpressionContent())
.withMisfireHandlingInstructionDoNothing();
TriggerBuilder<CronTrigger> trigger = TriggerBuilder.newTrigger()
.withIdentity(triggerKey)
.withDescription(taskTimeExpression.getExpressionDescription())
.withSchedule(schedBuilder)
.startAt(sdf.parse(taskTimeExpression.getExpressionStartDatetime()));
if(taskTimeExpression.getExpressionEndDatetime() != null){
trigger = trigger.endAt(sdf.parse(taskTimeExpression.getExpressionEndDatetime()));
}
Class<? extends Job> clazz = (Class<? extends Job>) Class.forName(taskTime.getTaskPackage() + "." + taskTime.getTaskClass());
JobDetail jobDetail = JobBuilder.newJob(clazz).withIdentity(jobKey).withDescription(taskTime.getTaskDescription()).build();
scheduler.scheduleJob(jobDetail, trigger.build());
} catch (SchedulerException e) {
throw ImppExceptionBuilder.newInstance()
.setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
.setErrorCode(ImppExceptionEnum.TASK_EXCEPTION.getCode())
.build();
} catch (ParseException e) {
throw ImppExceptionBuilder.newInstance()
.setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
.setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_FORMAT.getCode())
.setErrorDetail("表达式起止时间错误")
.setErrorSolution("请更改表达式起止时间")
.build();
} catch (ClassNotFoundException e) {
throw ImppExceptionBuilder.newInstance()
.setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
.setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
.setErrorDetail("定时任务包名及类名不正确")
.setErrorSolution("请重新输入定时任务包名及类名")
.build();
}
return taskTime;
} }
@Override @Override
@ -104,5 +271,33 @@ public class TaskTimeServiceImpl implements ITaskTimeService {
taskTimeRDao.updateByHqlWhere(where.toString(), "taskStatus", status); taskTimeRDao.updateByHqlWhere(where.toString(), "taskStatus", status);
} }
@Override
public void doTaskTimeLastDateByNameAndGroupName(String lastDate, String name, String groupName) {
taskTimeRDao.updateByProperties(
new String[]{"name","groupName"},new String[]{name,groupName},
"lastRunDateTime",lastDate);
}
@Override
public void executeTaskTimeById(long id) {
TaskTime taskTime = taskTimeRDao.getById(id);
JobKey jobKey = JobKey.jobKey(taskTime.getName(),taskTime.getGroupName());
try {
if (scheduler.checkExists(jobKey)) {
scheduler.triggerJob(jobKey);
} else {
throw ImppExceptionBuilder.newInstance()
.setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
.setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
.setErrorDetail("定时任务不存在")
.setErrorSolution("请重新输入任务名称和组名称")
.build();
}
} catch (SchedulerException e) {
throw ImppExceptionBuilder.newInstance()
.setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
.setErrorCode(ImppExceptionEnum.TASK_EXCEPTION.getCode())
.build();
}
}
} }

@ -0,0 +1,202 @@
package cn.estsh.i3plus.core.apiservice.util;
import cn.estsh.i3plus.platform.common.util.CommonConstWords;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import sun.misc.BASE64Encoder;
import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Properties;
/**
* @Description :
* @Reference :
* @Author : yunhao
* @CreateDate : 2018-11-14 19:24
* @Modify:
**/
public class MailUtil {
public static final Logger LOGGER = LoggerFactory.getLogger(MailUtil.class);
// 收件人
private Address[] to = null;
private Address[] cc = null;
private String from = "";
private String nick = "";
private String title = "";
private String content = "";
private String smtpHost = "";
private int smtpPort = 25;
private String content_type = "";
private String smtpUser = "";
private String smtpPassword = "";
private boolean isAuthenticationSMTP = false;
//初始化服务器邮箱参数
public MailUtil() {
try {
Properties mailInfo = PropertiesLoaderUtils.loadAllProperties("mail.properties");
this.smtpHost = mailInfo.get("mail.host").toString();
this.smtpPort = Integer.parseInt(mailInfo.get("mail.port").toString());
this.from = mailInfo.get("mail.user") + "";
this.nick = mailInfo.get("mail.nick") + "";
this.smtpUser = mailInfo.get("mail.user") + "";
this.smtpPassword = mailInfo.get("mail.password") + "";
this.isAuthenticationSMTP = true;
} catch (IOException e) {
e.printStackTrace();
}
}
/**
*
*
* @param aEmail
* Email
*/
public void setTo(String aEmail) {
String[] s = new String[1];
s[0] = aEmail;
this.to = getAddress(s);
}
/**
*
*
* @param Emails
* Email
*/
public void setTo(String[] Emails) {
this.to = getAddress(Emails);
}
/**
*
*
* @param aEmail
*
*/
public void setCC(String aEmail) {
String[] s = new String[1];
s[0] = aEmail;
this.cc = getAddress(s);
}
/**
*
*
* @param Emails
*
*/
public void setCC(String[] Emails) {
this.cc = getAddress(Emails);
}
/**
*
*
* @param mailTitle
*
*/
public void setSubject(String mailTitle) {
this.title = mailTitle;
}
/**
*
*
* @param mailContent
*
*/
public void setBody(String mailContent) {
this.content = mailContent;
}
/**
*
*
* @param contentType
* CommonConstWords.MAIL_MODE_TEXTMAIL_MODE_HTML
*/
public void setContentType(String contentType) {
this.content_type = contentType;
}
private Address[] getAddress(String[] add) {
Address[] a = new Address[add.length];
for (int i = 0; i < add.length; i++) {
try {
a[i] = new InternetAddress(add[i]);
} catch (AddressException ex) {
ex.printStackTrace();
}
}
return a;
}
/**
*
*/
public void send() {
try {
// 乱码
BASE64Encoder enc = new BASE64Encoder();
Properties server = new Properties();
server.put("mail.smtp.port", String.valueOf(this.smtpPort));
server.put("mail.smtp.host", this.smtpHost);
if (this.isAuthenticationSMTP) {
server.put("mail.smtp.auth", "true");
}
Session conn = Session.getInstance(server, null);
MimeMessage msg = new MimeMessage(conn);
if (nick != null && !"".equals(nick)) {
msg.setSubject("=?GB2312?B?" + enc.encode(nick.getBytes())+ "?=");
msg.setFrom(new InternetAddress(nick + " <" + from + ">"));
} else {
msg.setFrom(new InternetAddress(this.from));
}
// 收件人
if (this.to != null) {
msg.setRecipients(Message.RecipientType.TO, this.to);
}
// 抄送
if (this.cc != null) {
msg.setRecipients(Message.RecipientType.CC, this.cc);
}
msg.setSubject("=?GB2312?B?" + enc.encode(this.title.getBytes())+ "?=");
msg.setSubject(this.title);
// 是HTML格式的邮件
msg.setContent(this.content, this.content_type);
msg.saveChanges();
if (this.isAuthenticationSMTP) {
Transport transport = conn.getTransport("smtp");
transport.connect(this.smtpHost, this.smtpUser, this.smtpPassword);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
} else {
Transport.send(msg, msg.getAllRecipients());
}
LOGGER.info("邮件发送成功");
} catch (javax.mail.internet.AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
public boolean isHtmlModeMail() {
return this.content_type.equals(CommonConstWords.MAIL_MODE_HTML);
}
}

@ -0,0 +1,5 @@
mail.host = smtphm.qiye.163.com
mail.port = 25
mail.user = dongshang@estsh.com
mail.password = Aa111111
mail.nick = 东尚消息

@ -56,17 +56,16 @@ public class TestTaskTimeService extends TestBase {
public void testInsertTaskTime() { public void testInsertTaskTime() {
TaskTime taskTime = new TaskTime(); TaskTime taskTime = new TaskTime();
taskTime.setName("时间表达式"); taskTime.setName("时间表达式");
taskTime.setTimeId(1L); taskTime.setTimeExpressionId(1L);
taskTime.setTaskStartDateTime("2018-01-01 00:00:00"); taskTime.setTaskStartDateTimeRdd("2018-01-01 00:00:00");
taskTime.setTaskEndDateTime("2018-12-31 00:00:00"); taskTime.setTaskEndDateTimeRdd("2018-12-31 00:00:00");
taskTime.setLastRunDateTime("2018-11-03 00:00:00");
taskTime.setTaskTypeId(ImppEnumUtil.TASK_METHOD_TYPE.TYPE_GROUP.getValue()); taskTime.setTaskTypeId(ImppEnumUtil.TASK_METHOD_TYPE.TYPE_GROUP.getValue());
taskTime.setTaskStatus(CommonEnumUtil.DATA_STATUS.ENABLE.getValue()); taskTime.setTaskStatus(CommonEnumUtil.DATA_STATUS.ENABLE.getValue());
for (int i = 0; i < 50; i++) { for (int i = 0; i < 50; i++) {
taskTime.setId(null); taskTime.setId(null);
taskTime.setName("时间表达式"+i); taskTime.setName("时间表达式"+i);
taskTimeService.insertTaskTime(taskTime); taskTimeService.insertTaskTime(taskTime,null);
} }
System.out.println(JSON.toJSONString(taskTime)); System.out.println(JSON.toJSONString(taskTime));
} }
@ -80,7 +79,7 @@ public class TestTaskTimeService extends TestBase {
TaskTime taskTime = taskTimeService.getTaskTimeById("1057110613261684736"); TaskTime taskTime = taskTimeService.getTaskTimeById("1057110613261684736");
taskTime.setName("测试修改"); taskTime.setName("测试修改");
taskTimeService.updateTaskTime(taskTime); taskTimeService.updateTaskTime(taskTime,null);
} }
/** /**

@ -78,8 +78,10 @@ public class TestToolService extends TestBase {
public void testUpdateTool(){ public void testUpdateTool(){
Tool tool = toolService.getToolById("1057110613261684736"); Tool tool = toolService.getToolById("1057110613261684736");
tool.setName("测试修改"); tool.setName("测试修改");
if(tool != null){
toolService.updateTool(tool);
}
toolService.updateTool(tool);
} }
/** /**

@ -170,6 +170,12 @@
<version>4.12</version> <version>4.12</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<!-- JavaMail -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
</dependencies> </dependencies>
</dependencyManagement> </dependencyManagement>

Loading…
Cancel
Save