springboot quartz的封裝

引入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;
    }
  }
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章