引入quartz包,封装出一个在spring boot导入可用的jar包
目录接口:
SechdulerManager类,负责初始化和销毁scheduler,设计为单利模式,私有化构造器,整个应用维护一个scheduler。并配置sechduler相关配置信息。
public class SchedulerManager {
private static final Logger LOGGER = LoggerFactory.getLogger(SchedulerManager.class);
public static final String QUARTZ_THREAD_POOL_COUNT = "5";
private static Scheduler scheduler;
private SchedulerManager() {
}
public static Scheduler getInstanse() {
if (scheduler == null) {
init();
}
return scheduler;
}
public static void init() {
try {
Properties props = new Properties();
props.setProperty("org.quartz.scheduler.skipUpdateCheck", "true");
props.setProperty("org.quartz.jobStore.class", "org.quartz.simpl.RAMJobStore");
props.setProperty("org.quartz.threadPool.class", "org.quartz.simpl.SimpleThreadPool");
props.setProperty("org.quartz.threadPool.threadCount", "5");
SchedulerFactory schedulerFactory = new StdSchedulerFactory(props);
scheduler = schedulerFactory.getScheduler();
} catch (Exception var2) {
LOGGER.error("The Scheduler initialization error!", var2);
}
LOGGER.info("The Scheduler initialization completed!");
}
public static void destroy() {
try {
if (scheduler != null && !scheduler.isShutdown()) {
scheduler.shutdown(true);
scheduler = null;
}
} catch (Exception var1) {
LOGGER.error("The Scheduler shutdown error!", var1);
}
LOGGER.info("The Scheduler shutdown completed!");
}
}
JobManager类,任务管理类,继承ApplicationContextAware,获得applicationContext,从而获得容器中的sechduler bean。该类提供创建任务、添加任务、删除任务、修改任务、查询任务等接口。
@Component
public class JobManager implements ApplicationContextAware {
private static final Logger LOGGER = LoggerFactory.getLogger(JobManager.class);
public static final String TRIGGER_GROUP_NAME = "egsc_trigger";
public static final String TRIGGER_NAME_PERFIX = "egsc_trigger_name";
public static final String QUEUE_OBJECT_KEY = "queue_object_key";
private ApplicationContext applicationContext;
private JobManager() {
}
public boolean createJob(BusinessJobConfig jobConfig) {
StringBuilder jobNameBuilder = (new StringBuilder("egsc_job_name_")).append(jobConfig.getServiceName()).append("#").append(jobConfig.getMethodName());
if (StringUtils.isNotBlank(jobConfig.getId())) {
jobNameBuilder.append("#").append(jobConfig.getId());
}
String jobName = jobNameBuilder.toString();
String jobGroupName = "egsc_job_group_name_business_jobs";
if (this.isJobExist(jobName, jobGroupName)) {
LOGGER.debug("--------- 创建任务失败。任务已存在," + jobName);
return false;
} else {
String cronExpression = jobConfig.getCronExpression();
BusinessJob mj = new BusinessJob(jobName, cronExpression);
JobDataMap attributeMap = new JobDataMap();
attributeMap.put("businessJobInfo", jobConfig);
attributeMap.put("applicationContext", this.applicationContext);
mj.setAttributeMap(attributeMap);
this.addJob(mj);
LOGGER.debug("--------- 创建任务成功。任务名称:" + jobName);
return true;
}
}
public void addJob(AbstractJob job) {
Scheduler scheduler = SchedulerManager.getInstanse();
String jobName = job.getName();
String triggerName = "egsc_trigger_name at " + job.getName();
LOGGER.info("Add a job[" + jobName + "] start...");
try {
JobDetail jobDetail = JobBuilder.newJob(job.getClass()).withIdentity(jobName, job.getGroupName()).usingJobData(job.getAttributeMap()).build();
Trigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerName, "egsc_trigger").withSchedule(CronScheduleBuilder.cronSchedule(job.getCronExpression())).build();
scheduler.scheduleJob(jobDetail, trigger);
if (!scheduler.isShutdown()) {
scheduler.start();
}
} catch (Exception var7) {
LOGGER.error("Add a time in [" + job.getCronExpression() + "] triggered of the job [" + job.getName() + "] is error!", var7);
}
LOGGER.info("Add a job[" + jobName + "] end.");
}
public void modifyJobTime(String jobName, String cronExpression) {
Scheduler scheduler = SchedulerManager.getInstanse();
LOGGER.info("Modify a job[" + jobName + "] start...");
try {
String triggerName = "egsc_trigger_name at " + jobName;
TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, "egsc_trigger");
Trigger trigger = scheduler.getTrigger(triggerKey);
if (trigger != null) {
CronTrigger ct = (CronTrigger)trigger;
ct.getTriggerBuilder().withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)).startNow().build();
scheduler.resumeTrigger(triggerKey);
}
} catch (Exception var8) {
LOGGER.error("Add a time in [" + cronExpression + "] triggered of the job [" + jobName + "] is error!", var8);
}
LOGGER.info("Modify a job[" + jobName + "] end.");
}
public boolean removeJob(String jobName, String jobGroupName) {
Scheduler scheduler = SchedulerManager.getInstanse();
LOGGER.info("Remove a job[" + jobName + "] start...");
boolean b = false;
try {
JobKey jobKey = JobKey.jobKey(jobName, jobGroupName);
b = scheduler.deleteJob(jobKey);
} catch (Exception var6) {
LOGGER.error("Delete a job [" + jobName + "] is error!", var6);
}
LOGGER.info("Remove a job[" + jobName + "] end.");
return b;
}
public boolean isJobExist(String jobName, String jobGroupName) {
Scheduler scheduler = SchedulerManager.getInstanse();
LOGGER.info("Find a job[" + jobName + "] start...");
try {
GroupMatcher<JobKey> groupMatcher = GroupMatcher.groupContains(jobGroupName);
Set<JobKey> jobKeySet = scheduler.getJobKeys(groupMatcher);
Iterator var6 = jobKeySet.iterator();
while(var6.hasNext()) {
JobKey jobKey = (JobKey)var6.next();
if (jobKey.getName().equals(jobName)) {
return true;
}
}
} catch (Exception var8) {
LOGGER.error("Find a job[" + jobName + "] error.", var8);
}
LOGGER.info("Find a job[" + jobName + "] end.");
return false;
}
public List<Object[]> getAllRunningJob() {
Scheduler scheduler = SchedulerManager.getInstanse();
ArrayList list = null;
try {
List<JobExecutionContext> runningJobs = scheduler.getCurrentlyExecutingJobs();
if (CollectionUtils.isEmpty(runningJobs)) {
return null;
}
list = new ArrayList(runningJobs.size());
Iterator var4 = runningJobs.iterator();
while(var4.hasNext()) {
JobExecutionContext jeContext = (JobExecutionContext)var4.next();
JobDetail jobDetail = jeContext.getJobDetail();
Trigger jobTrigger = jeContext.getTrigger();
JobDataMap jobDataMap = jobDetail.getJobDataMap();
list.add(new Object[]{jobDetail, jobTrigger, jobDataMap});
}
} catch (SchedulerException var9) {
LOGGER.error(var9.getMessage());
}
return list;
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public ApplicationContext getApplicationContext() {
return this.applicationContext;
}
}
BusinessJobConfig类,任务配置类。
public class BusinessJobConfig {
private String serviceName;
private String methodName;
private String cronExpression;
private String category;
private String ips;
private String status;
private String creator;
private String creatorId;
private Date createDt;
private String lastUpdator;
private String lastUpdatorId;
private Date lastUpdateDt;
private boolean runAsAdmin = false;
private Map<String, Object> params;
private String id;
public BusinessJobConfig() {
}
public boolean isRunAsAdmin() {
return this.runAsAdmin;
}
public void setRunAsAdmin(boolean runAsAdmin) {
this.runAsAdmin = runAsAdmin;
}
public String getServiceName() {
return this.serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public String getMethodName() {
return this.methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
public String getCronExpression() {
return this.cronExpression;
}
public void setCronExpression(String cronExpression) {
this.cronExpression = cronExpression;
}
public String getStatus() {
return this.status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCreator() {
return this.creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public String getCreatorId() {
return this.creatorId;
}
public void setCreatorId(String creatorId) {
this.creatorId = creatorId;
}
@JsonFormat(
pattern = "yyyy-MM-dd HH:mm:ss"
)
public Date getCreateDt() {
return this.createDt;
}
public void setCreateDt(Date createDt) {
this.createDt = createDt;
}
public String getLastUpdator() {
return this.lastUpdator;
}
public void setLastUpdator(String lastUpdator) {
this.lastUpdator = lastUpdator;
}
public String getLastUpdatorId() {
return this.lastUpdatorId;
}
public void setLastUpdatorId(String lastUpdatorId) {
this.lastUpdatorId = lastUpdatorId;
}
@JsonFormat(
pattern = "yyyy-MM-dd HH:mm:ss"
)
public Date getLastUpdateDt() {
return this.lastUpdateDt;
}
public void setLastUpdateDt(Date lastUpdateDt) {
this.lastUpdateDt = lastUpdateDt;
}
public String getCategory() {
return this.category;
}
public void setCategory(String category) {
this.category = category;
}
public String getIps() {
return this.ips;
}
public void setIps(String ips) {
this.ips = ips;
}
public Map<String, Object> getParams() {
return this.params;
}
public void setParams(Map<String, Object> params) {
this.params = params;
}
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
}
AbstractJob类,继承Job类,JobDataMap保存任务执行时的数据,抽象了setAttribute方法和getAttribute方法, 定义了一些获取任务信息的抽象方法。
abstract class AbstractJob implements Job {
public static final String JOB_NAME_PREFIX = "egsc_job_name_";
public static final String JOB_GROUP_NAME = "egsc_job_group_name_";
private JobDataMap attributeMap;
public AbstractJob() {
}
public abstract String getName();
public abstract String getGroupName();
public abstract String getCronExpression();
protected String genDefaultName() {
return "egsc_job_name_" + getUUID();
}
protected String getGroupDefaultName() {
return "egsc_job_name_";
}
public void addAttribute(String name, String value) {
if (CollectionUtils.isEmpty(this.attributeMap)) {
this.attributeMap = new JobDataMap();
}
this.attributeMap.put(name, value);
}
public Object getAttribute(String name) {
return !CollectionUtils.isEmpty(this.attributeMap) && this.attributeMap.containsKey(name) ? this.attributeMap.get(name) : null;
}
public JobDataMap getAttributeMap() {
return CollectionUtils.isEmpty(this.attributeMap) ? new JobDataMap() : this.attributeMap;
}
public void setAttributeMap(JobDataMap attributeMap) {
this.attributeMap = attributeMap;
}
private static final synchronized String getUUID() {
return UUID.randomUUID().toString().replace("-", "");
}
}
BussinessJob类,继承AbstractJob,实现了job的execute方法,通过反射调用任务类的作业方法。
public class BusinessJob extends AbstractJob {
private static final Logger logger = LoggerFactory.getLogger(BusinessJob.class);
public static final String BUSINESS_JOB_GROUP_NAME = "egsc_job_group_name_business_jobs";
private String jobName;
private String cronExpression;
public BusinessJob() {
}
public BusinessJob(String jobName, String cronExpression) {
this.jobName = jobName;
this.cronExpression = cronExpression;
}
public void execute(JobExecutionContext context) throws JobExecutionException {
JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
BusinessJobConfig businessJobInfo = (BusinessJobConfig)jobDataMap.get("businessJobInfo");
ApplicationContext appContext = (ApplicationContext)jobDataMap.get("applicationContext");
RedisUtils redisUtils = (RedisUtils)appContext.getBean("redisUtils");
JobDetail jobDetail = context.getJobDetail();
String jobName = "";
if (null != jobDetail) {
jobName = jobDetail.getKey().getName();
}
// 作业类的bean名称
String serviceName = businessJobInfo.getServiceName();
// 作业类需要执行的方法名
String methodName = businessJobInfo.getMethodName();
// 方法需要的参数
Map<String, Object> params = businessJobInfo.getParams();
// 获得容器中的作业类的bean
Object bjs = appContext.getBean(serviceName);
// 从上下文环境中获得应用名
String appName = appContext.getEnvironment().getProperty("spring.application.name");
if (StringUtils.isBlank(appName)) {
logger.error("error 缺少配置 spring.application.name");
} else {
// 反射调用作业类的方法
Class clazz = bjs.getClass();
try {
Method m1 = null;
if (null == params) {
m1 = clazz.getDeclaredMethod(methodName);
} else {
m1 = clazz.getDeclaredMethod(methodName, Map.class);
}
if (null == m1) {
logger.error("execute Job Method is null");
return;
}
logger.info("execute start:" + businessJobInfo);
if (redisUtils.isvalidLockBusiness(jobName, 30L)) {
logger.info("JOB正在运行中,jobName = " + jobName);
return;
}
redisUtils.unlockBusiness(jobName);
if (!redisUtils.lockBusiness(jobName, 30L)) {
logger.info("JOB加锁失败,jobName = " + jobName);
return;
}
Map<String, String> map = (Map)redisUtils.get(jobName);
if (!this.isRunning(appContext, appName, map)) {
if (businessJobInfo.isRunAsAdmin()) {
SuperviserService superviserService = (SuperviserService)appContext.getBean("superviserServiceImpl");
superviserService.loginAsAdmin();
}
Map<String, String> jobMap = new HashMap();
jobMap.put("jobName", jobName);
jobMap.put("ip", IPUtils.getIp());
redisUtils.set(jobName, jobMap);
if (null == params) {
m1.invoke(bjs);
} else {
m1.invoke(bjs, params);
}
redisUtils.del(new String[]{jobName});
logger.info("execute end:" + businessJobInfo);
}
} catch (SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException var17) {
logger.error(var17.getMessage(), var17);
}
redisUtils.unlockBusiness(jobName);
}
}
private boolean isRunning(ApplicationContext appContext, String appName, Map<String, String> jobMap) {
if (null != appContext.getBean(DiscoveryClient.class) && null != jobMap && !StringUtils.isBlank(appName)) {
String ip = (String)jobMap.get("ip");
if (StringUtils.isNotBlank(ip)) {
DiscoveryClient discoveryClient = (DiscoveryClient)appContext.getBean(DiscoveryClient.class);
List<ServiceInstance> instanceList = discoveryClient.getInstances(appName);
if (CollectionUtils.isEmpty(instanceList)) {
return false;
}
Iterator var7 = instanceList.iterator();
while(var7.hasNext()) {
ServiceInstance instance = (ServiceInstance)var7.next();
if (null != instance && ip.equals(instance.getHost())) {
logger.error("JOB正在运行中,jobName = " + (String)jobMap.get("jobName") + ", 执行节点ip = " + ip);
return true;
}
}
}
return false;
} else {
return false;
}
}
public String getCronExpression() {
return this.cronExpression;
}
public String getName() {
return this.jobName;
}
public String getGroupName() {
return "egsc_job_group_name_business_jobs";
}
}
QuartzAdapter类,注册成bean,从applicationContext中获取用户实现的bean jobConfig,获取所有的任务配置。
@Component
public class QuartzAdapter {
private static final Logger logger = LoggerFactory.getLogger(QuartzAdapter.class);
public QuartzAdapter() {
}
public List<BusinessJobConfig> findAllJobConfigs(ApplicationContext applicationContext) {
List<BusinessJobConfig> jobInfos = new ArrayList();
JobConfigService jobConfigService = null;
try {
jobConfigService = (JobConfigService)applicationContext.getBean("jobConfig");
if (jobConfigService != null) {
jobInfos = jobConfigService.getAllJobConfigs();
}
} catch (Exception var5) {
logger.info(var5.getMessage());
}
if (jobInfos == null) {
logger.info("没有得到JOB配置信息!");
jobInfos = new ArrayList();
}
return (List)jobInfos;
}
}
JobMonitor类,任务监控类,依赖QuartzAdapter和JobManager,启动任务。
@Component
public class JobMonitor {
@Autowired
private QuartzAdapter quartzAdapterImpl;
@Autowired
private JobManager jobManager;
private boolean active = false;
public JobMonitor() {
}
public void start() {
List<BusinessJobConfig> jobConfigs = this.quartzAdapterImpl.findAllJobConfigs(this.jobManager.getApplicationContext());
if (!this.active) {
if (CollectionUtils.isEmpty(jobConfigs)) {
return;
}
Iterator var2 = jobConfigs.iterator();
while(var2.hasNext()) {
BusinessJobConfig jobConfig = (BusinessJobConfig)var2.next();
if (!JobStatus.DISABLE.getValue().equals(jobConfig.getStatus())) {
this.jobManager.createJob(jobConfig);
}
}
this.active = true;
}
}
public void stop() {
if (this.active) {
this.active = false;
}
}
public void restart() {
this.stop();
this.start();
}
public boolean isActive() {
return this.active;
}
public List<BusinessJobConfig> getBusinessJobInfoList() {
return null;
}
}
JobStatus枚举类
public enum JobStatus {
ENABLE("1"),
DISABLE("0");
private String value;
private JobStatus(String value) {
this.value = value;
}
public String getValue() {
return this.value;
}
}
监听器:
@WebListener
public class BusinessJobListener implements ServletContextListener {
@Autowired
private JobMonitor monitor;
public BusinessJobListener() {
}
public void contextInitialized(ServletContextEvent sce) {
if (this.monitor != null && !this.monitor.isActive()) {
this.monitor.start();
}
}
public void contextDestroyed(ServletContextEvent sce) {
if (this.monitor != null && this.monitor.isActive()) {
this.monitor.stop();
}
}
}
JobService对外提供服务:
@Component
public class JobService {
@Autowired
private JobManager jobManager;
private static final Logger LOGGER = LoggerFactory.getLogger(JobService.class);
private JobService() {
}
public boolean createJob(BusinessJobConfig jobConfig) {
if (null == jobConfig) {
LOGGER.info("参数jobConfig 不能为空!");
return false;
} else if (!StringUtils.isBlank(jobConfig.getServiceName()) && !StringUtils.isBlank(jobConfig.getMethodName()) && !StringUtils.isBlank(jobConfig.getCronExpression())) {
if (null == jobConfig.getParams()) {
jobConfig.setParams(new HashMap());
}
if (this.jobManager.createJob(jobConfig)) {
LOGGER.info("创建任务成功。服务名称:" + jobConfig.getServiceName() + " 方法名称:" + jobConfig.getMethodName() + " 表达式:" + jobConfig.getCronExpression() + " id:" + jobConfig.getId());
return true;
} else {
LOGGER.info("创建任务失败。任务已存在," + jobConfig.getServiceName() + " 方法名称:" + jobConfig.getMethodName() + " id:" + jobConfig.getId());
return false;
}
} else {
LOGGER.info("创建任务失败,由于服务名称、方法名称或表达式为空。服务名称:" + jobConfig.getServiceName() + " 方法名称:" + jobConfig.getMethodName() + " 表达式:" + jobConfig.getCronExpression() + " id:" + jobConfig.getId());
return false;
}
}
public boolean removeJob(String serviceName, String methodName) {
return this.removeJob(serviceName, methodName, "");
}
public boolean removeJob(String serviceName, String methodName, String id) {
if (!StringUtils.isBlank(serviceName) && !StringUtils.isBlank(methodName)) {
return this.removeJob(this.getJobName(serviceName, methodName, id));
} else {
LOGGER.error("参数serviceName 和 methodName 不能为空!");
return false;
}
}
public boolean removeJob(String jobName) {
if (StringUtils.isBlank(jobName)) {
LOGGER.error("参数jobName 不能为空!");
return false;
} else {
return this.jobManager.removeJob(jobName, "egsc_job_group_name_business_jobs");
}
}
public boolean isJobExist(String serviceName, String methodName) {
return this.isJobExist(serviceName, methodName, "");
}
public boolean isJobExist(String serviceName, String methodName, String id) {
if (!StringUtils.isBlank(serviceName) && !StringUtils.isBlank(methodName)) {
return this.isJobExist(this.getJobName(serviceName, methodName, id));
} else {
LOGGER.error("参数serviceName 和 methodName 不能为空!");
return false;
}
}
public boolean isJobExist(String jobName) {
if (StringUtils.isBlank(jobName)) {
LOGGER.error("参数jobName 不能为空!");
return false;
} else {
return this.jobManager.isJobExist(jobName, "egsc_job_group_name_business_jobs");
}
}
public List<Object[]> getAllRunningJob() {
return this.jobManager.getAllRunningJob();
}
public String getJobName(String serviceName, String methodName, String id) {
if (!StringUtils.isBlank(serviceName) && !StringUtils.isBlank(methodName)) {
StringBuilder jobName = (new StringBuilder("egsc_job_name_")).append(serviceName).append("#").append(methodName);
if (StringUtils.isNotBlank(id)) {
jobName.append("#").append(id);
}
return jobName.toString();
} else {
return "";
}
}
}
实现,目录结构
AccJobProp为配置类,加载配置信息。
@Component
@ConfigurationProperties(prefix = "egsc.schedule")
public class AccJobProp {
private List<BusinessJobConfig> jobs = new ArrayList<>();
public List<BusinessJobConfig> getJobs() {
return this.jobs;
}
public void setJobs(List<BusinessJobConfig> jobs) {
this.jobs = jobs;
}
}
配置信息:
egsc.schedule.jobs[0].serviceName=repeatSendFailMsgJob
egsc.schedule.jobs[0].methodName=run
egsc.schedule.jobs[0].cronExpression=0 0 0/1 * * ?
egsc.schedule.jobs[0].status=1
egsc.schedule.jobs[0].category=
egsc.schedule.jobs[0].ips=192.168.175.1
egsc.schedule.jobs[0].creator=
egsc.schedule.jobs[0].creatorId=
egsc.schedule.jobs[0].privateDatecreateDt=
egsc.schedule.jobs[0].lastUpdator=
egsc.schedule.jobs[0].lastUpdatorId=
egsc.schedule.jobs[0].privateDatelastUpdateDt=
egsc.schedule.jobs[1].serviceName=demoJob2
egsc.schedule.jobs[1].methodName=run
egsc.schedule.jobs[1].cronExpression=*/5 * * * * ?
egsc.schedule.jobs[1].category=
egsc.schedule.jobs[1].ips=192.168.175.1
egsc.schedule.jobs[1].status=1
egsc.schedule.jobs[1].creator=
egsc.schedule.jobs[1].creatorId=
egsc.schedule.jobs[1].privateDatecreateDt=
egsc.schedule.jobs[1].lastUpdator=
egsc.schedule.jobs[1].lastUpdatorId=
egsc.schedule.jobs[1].privateDatelastUpdateDt=
jobConfig bean
@Component("jobConfig")
public class PropertyJobConfigService implements JobConfigService {
@Resource
AccJobProp accJobProp;
@Override
public List<BusinessJobConfig> getAllJobConfigs() {
return accJobProp.getJobs();
}
}
AccJobService
@Component("accJobService")
public class AccJobService {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private JobService jobService;
/**
* 创建定时任务
*
* @param messageId void
*/
public void createFailMessageJob(String messageId) {
log.info("创建失败消息job,失败后每隔十五分钟重发一次,共重发三次");
String jobName = jobService.getJobName("repeatSendFourJob", "run", messageId);
if (jobService.isJobExist(jobName)) {
log.info("{}--任务已存在", jobName);
} else {
BusinessJobConfig jobConfig = new BusinessJobConfig();
jobConfig.setServiceName("repeatSendFourJob");
jobConfig.setMethodName("run");
jobConfig.setId(messageId);
jobConfig.setCronExpression("0/15 * * * * ?");
jobConfig.setStatus("1");
jobConfig.setRunAsAdmin(false);
Map<String, Object> params = new HashMap<String, Object>();
params.put("jobName", jobName);
params.put("messageId", messageId);
jobConfig.setParams(params);
jobService.createJob(jobConfig);
}
}
}
两个任务类
@Component("repeatSendFailMsgJob")
public class RepeatSendFailMsgJob {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
@Resource(name = "informationRecordServiceImpl")
private InformationRecordService informationRecordService;
@Resource(name = "iotbusServiceImpl")
private IotbusService iotbusService;
/**
* 每隔一小时重发当天失败记录
*/
public void run() {
logger.info("---------每隔一小时重发当天失败记录---------");
try {
List<BusMsg<SendInfo>> infoList = informationRecordService.getRecordDayStatus();
iotbusService.repeatSendToGateway(infoList);
} catch (Exception e) {
logger.error("重发消息异常");
}
}
}
@Component("repeatSendFourJob")
public class RepeatSendFourJob {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
private static int count = 0;
@Autowired
private JobService jobService;
@Resource(name = "iotbusServiceImpl")
private IotbusService iotbusService;
@Resource(name = "informationRecordServiceImpl")
private InformationRecordService informationRecordService;
/**
* 重发三次
*
* @param params void
*/
public void run(Map params) {
logger.info("单条失败重发第{}次", ++count);
String messageId = (String) params.get("messageId");
BusMsg<SendInfo> busMsg = informationRecordService.getRecordByStatus(messageId, 1);
iotbusService.repeatSendToGateway(busMsg);
String jobName = (String) params.get("jobName");
if (count > 2) {
logger.info("已发三条,删除任务--{}", jobName);
jobService.removeJob(jobName);
count = 0;
}
}
}