Search in sources :

Example 1 with JobConfig

use of com.jeesuite.scheduler.model.JobConfig in project jeesuite-libs by vakinge.

the class ZkJobRegistry method execCommond.

private void execCommond(MonitorCommond cmd) {
    if (cmd == null)
        return;
    JobConfig config = schedulerConfgs.get(cmd.getJobName());
    String key = cmd.getJobGroup() + ":" + cmd.getJobName();
    final AbstractJob abstractJob = JobContext.getContext().getAllJobs().get(key);
    if (MonitorCommond.TYPE_EXEC == cmd.getCmdType()) {
        if (config.isRunning()) {
            logger.info("任务正在执行中,请稍后再执行");
            return;
        }
        if (abstractJob != null) {
            JobContext.getContext().submitSyncTask(new Runnable() {

                @Override
                public void run() {
                    try {
                        logger.info("begin execute job[{}] by MonitorCommond", abstractJob.getJobName());
                        abstractJob.doJob(JobContext.getContext());
                    } catch (Exception e) {
                        logger.error(abstractJob.getJobName(), e);
                    }
                }
            });
        } else {
            logger.warn("Not found job by key:{} !!!!", key);
        }
    } else if (MonitorCommond.TYPE_STATUS_MOD == cmd.getCmdType() || MonitorCommond.TYPE_CRON_MOD == cmd.getCmdType()) {
        if (config != null) {
            if (MonitorCommond.TYPE_STATUS_MOD == cmd.getCmdType()) {
                config.setActive("1".equals(cmd.getBody()));
            } else {
                try {
                    new CronExpression(cmd.getBody().toString());
                } catch (Exception e) {
                    throw new RuntimeException("cron表达式格式错误");
                }
                abstractJob.resetTriggerCronExpr(cmd.getBody().toString());
                config.setCronExpr(cmd.getBody().toString());
            }
            updateJobConfig(config);
            if (JobContext.getContext().getConfigPersistHandler() != null) {
                JobContext.getContext().getConfigPersistHandler().persist(config);
            }
        }
    }
}
Also used : AbstractJob(com.jeesuite.scheduler.AbstractJob) CronExpression(org.quartz.CronExpression) JobConfig(com.jeesuite.scheduler.model.JobConfig)

Example 2 with JobConfig

use of com.jeesuite.scheduler.model.JobConfig in project jeesuite-libs by vakinge.

the class ZkJobRegistry method setRuning.

@Override
public void setRuning(String jobName, Date fireTime) {
    updatingStatus = false;
    try {
        JobConfig config = getConf(jobName, false);
        config.setRunning(true);
        config.setLastFireTime(fireTime);
        config.setModifyTime(Calendar.getInstance().getTimeInMillis());
        config.setErrorMsg(null);
        // 更新本地
        schedulerConfgs.put(jobName, config);
        try {
            if (zkAvailabled)
                zkClient.writeData(getPath(config), JsonUtils.toJson(config));
        } catch (Exception e) {
            checkZkAvailabled();
            logger.warn(String.format("Job[{}] setRuning error...", jobName), e);
        }
    } finally {
        updatingStatus = false;
    }
}
Also used : JobConfig(com.jeesuite.scheduler.model.JobConfig)

Example 3 with JobConfig

use of com.jeesuite.scheduler.model.JobConfig in project jeesuite-libs by vakinge.

the class ZkJobRegistry method afterPropertiesSet.

@Override
public void afterPropertiesSet() throws Exception {
    ZkConnection zkConnection = new ZkConnection(zkServers);
    zkClient = new ZkClient(zkConnection, 10000);
    // 
    zkCheckTask = Executors.newScheduledThreadPool(1);
    zkCheckTask.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {
            if (schedulerConfgs.isEmpty())
                return;
            List<String> activeNodes = null;
            try {
                activeNodes = zkClient.getChildren(nodeStateParentPath);
                zkAvailabled = true;
            } catch (Exception e) {
                checkZkAvailabled();
                activeNodes = new ArrayList<>(JobContext.getContext().getActiveNodes());
            }
            if (!activeNodes.contains(JobContext.getContext().getNodeId())) {
                zkClient.createEphemeral(nodeStateParentPath + "/" + JobContext.getContext().getNodeId());
                logger.info("node[{}] re-join task clusters", JobContext.getContext().getNodeId());
            }
            // 对节点列表排序
            Collections.sort(activeNodes);
            // 本地缓存的所有jobs
            Collection<JobConfig> jobConfigs = schedulerConfgs.values();
            // 
            for (JobConfig jobConfig : jobConfigs) {
                // 如果本地任务指定的执行节点不在当前实际的节点列表,重新指定
                if (!activeNodes.contains(jobConfig.getCurrentNodeId())) {
                    // 指定当前节点为排序后的第一个节点
                    String newExecuteNodeId = activeNodes.get(0);
                    jobConfig.setCurrentNodeId(newExecuteNodeId);
                    logger.warn("Job[{}-{}] currentNodeId[{}] not in activeNodeList, assign new ExecuteNodeId:{}", jobConfig.getGroupName(), jobConfig.getJobName(), jobConfig.getCurrentNodeId(), newExecuteNodeId);
                }
            }
        }
    }, 60, 30, TimeUnit.SECONDS);
}
Also used : ZkClient(org.I0Itec.zkclient.ZkClient) Collection(java.util.Collection) ArrayList(java.util.ArrayList) List(java.util.List) ZkConnection(org.I0Itec.zkclient.ZkConnection) JobConfig(com.jeesuite.scheduler.model.JobConfig)

Example 4 with JobConfig

use of com.jeesuite.scheduler.model.JobConfig in project jeesuite-libs by vakinge.

the class ZkJobRegistry method register.

@Override
public synchronized void register(JobConfig conf) {
    // 是否第一个启动节点
    boolean isFirstNode = false;
    Calendar now = Calendar.getInstance();
    long currentTimeMillis = now.getTimeInMillis();
    conf.setModifyTime(currentTimeMillis);
    if (groupPath == null) {
        groupPath = ROOT + conf.getGroupName();
    }
    if (nodeStateParentPath == null) {
        nodeStateParentPath = groupPath + "/nodes";
    }
    String path = getPath(conf);
    final String jobName = conf.getJobName();
    if (!zkClient.exists(nodeStateParentPath)) {
        isFirstNode = true;
        zkClient.createPersistent(nodeStateParentPath, true);
    } else {
        // 检查是否有节点
        if (!isFirstNode) {
            isFirstNode = zkClient.getChildren(nodeStateParentPath).size() == 0;
        }
    }
    if (!zkClient.exists(path)) {
        zkClient.createPersistent(path, true);
    }
    // 是否要更新ZK的conf配置
    boolean updateConfInZK = isFirstNode;
    if (!updateConfInZK) {
        JobConfig configFromZK = getConfigFromZK(path, null);
        if (configFromZK != null) {
            // 3.配置文件修改是30分钟前
            if (!StringUtils.equals(configFromZK.getCronExpr(), conf.getCronExpr())) {
                updateConfInZK = true;
            } else if (configFromZK.getNextFireTime() != null && configFromZK.getNextFireTime().before(now.getTime())) {
                updateConfInZK = true;
            } else if (currentTimeMillis - configFromZK.getModifyTime() > TimeUnit.MINUTES.toMillis(30)) {
                updateConfInZK = true;
            } else {
                if (!JobContext.getContext().getNodeId().equals(configFromZK.getCurrentNodeId())) {
                    List<String> nodes = zkClient.getChildren(nodeStateParentPath);
                    updateConfInZK = !nodes.contains(configFromZK.getCurrentNodeId());
                }
            }
        } else {
            // zookeeper 该job不存在?
            updateConfInZK = true;
        }
        // 拿ZK上的配置覆盖当前的
        if (!updateConfInZK) {
            conf = configFromZK;
        }
    }
    if (updateConfInZK) {
        conf.setCurrentNodeId(JobContext.getContext().getNodeId());
        zkClient.writeData(path, JsonUtils.toJson(conf));
    }
    schedulerConfgs.put(conf.getJobName(), conf);
    // 订阅同步信息变化
    zkClient.subscribeDataChanges(path, new IZkDataListener() {

        @Override
        public void handleDataDeleted(String dataPath) throws Exception {
            schedulerConfgs.remove(jobName);
        }

        @Override
        public void handleDataChange(String dataPath, Object data) throws Exception {
            if (data == null)
                return;
            JobConfig _jobConfig = JsonUtils.toObject(data.toString(), JobConfig.class);
            schedulerConfgs.put(jobName, _jobConfig);
        }
    });
    // 
    regAndSubscribeNodeEvent();
    logger.info("finish register schConfig:{}", ToStringBuilder.reflectionToString(conf, ToStringStyle.MULTI_LINE_STYLE));
}
Also used : Calendar(java.util.Calendar) IZkDataListener(org.I0Itec.zkclient.IZkDataListener) JobConfig(com.jeesuite.scheduler.model.JobConfig)

Example 5 with JobConfig

use of com.jeesuite.scheduler.model.JobConfig in project jeesuite-libs by vakinge.

the class ZkJobRegistry method setStoping.

@Override
public void setStoping(String jobName, Date nextFireTime, Exception e) {
    updatingStatus = false;
    try {
        JobConfig config = getConf(jobName, false);
        config.setRunning(false);
        config.setNextFireTime(nextFireTime);
        config.setModifyTime(Calendar.getInstance().getTimeInMillis());
        config.setErrorMsg(e == null ? null : e.getMessage());
        // 更新本地
        schedulerConfgs.put(jobName, config);
        try {
            if (zkAvailabled)
                zkClient.writeData(getPath(config), JsonUtils.toJson(config));
        } catch (Exception ex) {
            checkZkAvailabled();
            logger.warn(String.format("Job[{}] setStoping error...", jobName), ex);
        }
    } finally {
        updatingStatus = false;
    }
}
Also used : JobConfig(com.jeesuite.scheduler.model.JobConfig)

Aggregations

JobConfig (com.jeesuite.scheduler.model.JobConfig)12 AbstractJob (com.jeesuite.scheduler.AbstractJob)1 JobGroupInfo (com.jeesuite.scheduler.model.JobGroupInfo)1 ArrayList (java.util.ArrayList)1 Calendar (java.util.Calendar)1 Collection (java.util.Collection)1 Date (java.util.Date)1 List (java.util.List)1 IZkDataListener (org.I0Itec.zkclient.IZkDataListener)1 ZkClient (org.I0Itec.zkclient.ZkClient)1 ZkConnection (org.I0Itec.zkclient.ZkConnection)1 CronExpression (org.quartz.CronExpression)1 SchedulerException (org.quartz.SchedulerException)1 TriggerKey (org.quartz.TriggerKey)1