Java Code Examples for org.quartz.CronExpression#isValidExpression()

The following examples show how to use org.quartz.CronExpression#isValidExpression() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: QssService.java    From seed with Apache License 2.0 6 votes vote down vote up
/**
 * 更新CronExpression
 */
@Transactional(rollbackFor=Exception.class)
boolean updateCron(long taskId, String cron){
    if(!CronExpression.isValidExpression(cron)){
        throw new IllegalArgumentException("CronExpression不正确");
    }
    Optional<ScheduleTask> taskOptional = scheduleTaskRepository.findById(taskId);
    if(!taskOptional.isPresent()){
        throw new RuntimeException("不存在的任务:taskId=[" + taskId + "]");
    }
    ScheduleTask task = taskOptional.get();
    task.setCron(cron);
    boolean flag = 1 == scheduleTaskRepository.updateCronById(cron, taskId);
    try (Jedis jedis = jedisPool.getResource()) {
        jedis.publish(SeedConstants.CHANNEL_SUBSCRIBER, JSON.toJSONString(task));
    }
    return flag;
}
 
Example 2
Source File: ProcessPlatform.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public String getCron() {
	if (StringUtils.isNotEmpty(this.cron) && CronExpression.isValidExpression(this.cron)) {
		return this.cron;
	} else {
		return DEFAULT_CRON;
	}
}
 
Example 3
Source File: QuartzJobServiceImpl.java    From eladmin with Apache License 2.0 5 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class)
public void create(QuartzJob resources) {
    if (!CronExpression.isValidExpression(resources.getCronExpression())){
        throw new BadRequestException("cron表达式格式错误");
    }
    resources = quartzJobRepository.save(resources);
    quartzManage.addJob(resources);
}
 
Example 4
Source File: Query.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public String getCron() {
	if (StringUtils.isNotEmpty(this.cron) && CronExpression.isValidExpression(this.cron)) {
		return this.cron;
	} else {
		return DEFAULT_CRON;
	}
}
 
Example 5
Source File: Query.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public String getCron() {
	if (StringUtils.isNotEmpty(this.cron) && CronExpression.isValidExpression(this.cron)) {
		return this.cron;
	} else {
		return DEFAULT_CRON;
	}
}
 
Example 6
Source File: ProcessPlatform.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public String getCron() {
	if (StringUtils.isNotEmpty(this.cron) && CronExpression.isValidExpression(this.cron)) {
		return this.cron;
	} else {
		return DEFAULT_CRON;
	}
}
 
Example 7
Source File: JobScheduler.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Schedule a {@link ScheduledJob} with a cron expression defined in the entity.
 *
 * <p>Reschedules job if the job already exists.
 *
 * <p>If active is false, it unschedules the job
 *
 * @param scheduledJob the {@link ScheduledJob} to schedule
 */
public synchronized void schedule(ScheduledJob scheduledJob) {
  String id = scheduledJob.getId();
  String cronExpression = scheduledJob.getCronExpression();
  String name = scheduledJob.getName();

  // Validate cron expression
  if (!CronExpression.isValidExpression(cronExpression)) {
    throw new MolgenisValidationException(
        singleton(
            new ConstraintViolation("Invalid cronexpression '" + cronExpression + "'", null)));
  }

  try {
    // If already scheduled, remove it from the quartzScheduler
    if (quartzScheduler.checkExists(new JobKey(id, SCHEDULED_JOB_GROUP))) {
      unschedule(id);
    }

    // If not active, do not schedule it
    if (!scheduledJob.isActive()) {
      return;
    }

    // Schedule with 'cron' trigger
    Trigger trigger =
        newTrigger()
            .withIdentity(id, SCHEDULED_JOB_GROUP)
            .withSchedule(cronSchedule(cronExpression))
            .build();
    schedule(scheduledJob, trigger);

    LOG.info("Scheduled Job '{}' with trigger '{}'", name, trigger);
  } catch (SchedulerException e) {
    LOG.error("Error schedule job", e);
    throw new ScheduledJobException("Error schedule job", e);
  }
}
 
Example 8
Source File: ProcessPlatform.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public String getCron() {
	if (StringUtils.isNotEmpty(this.cron) && CronExpression.isValidExpression(this.cron)) {
		return this.cron;
	} else {
		return DEFAULT_CRON;
	}
}
 
Example 9
Source File: NotebookRestApi.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
/**
 * Register cron job REST API.
 *
 * @param message - JSON with cron expressions.
 * @return JSON with status.OK
 * @throws IOException
 * @throws IllegalArgumentException
 */
@POST
@Path("cron/{noteId}")
@ZeppelinApi
public Response registerCronJob(@PathParam("noteId") String noteId, String message)
    throws IOException, IllegalArgumentException {
  LOG.info("Register cron job note={} request cron msg={}", noteId, message);

  CronRequest request = CronRequest.fromJson(message);

  Note note = notebook.getNote(noteId);
  checkIfNoteIsNotNull(note);
  checkIfUserCanRun(noteId, "Insufficient privileges you cannot set a cron job for this note");
  checkIfNoteSupportsCron(note);

  if (!CronExpression.isValidExpression(request.getCronString())) {
    return new JsonResponse<>(Status.BAD_REQUEST, "wrong cron expressions.").build();
  }

  Map<String, Object> config = note.getConfig();
  config.put("cron", request.getCronString());
  config.put("releaseresource", request.getReleaseResource());
  note.setConfig(config);
  schedulerService.refreshCron(note.getId());

  return new JsonResponse<>(Status.OK).build();
}
 
Example 10
Source File: ProcessPlatform.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public String getCron() {
	if (StringUtils.isNotEmpty(this.cron) && CronExpression.isValidExpression(this.cron)) {
		return this.cron;
	} else {
		return DEFAULT_CRON;
	}
}
 
Example 11
Source File: QuartzJobServiceImpl.java    From DimpleBlog with Apache License 2.0 5 votes vote down vote up
@Override
public int updateQuartzJob(QuartzJob quartzJob) {
    if (!CronExpression.isValidExpression(quartzJob.getCronExpression())) {
        throw new CustomException("Cron表达式错误");
    }
    quartzManage.updateJobCron(quartzJob);
    return quartzJobMapper.updateQuartzJob(quartzJob);
}
 
Example 12
Source File: JobController.java    From FEBS-Cloud with Apache License 2.0 5 votes vote down vote up
@GetMapping("cron/check")
public boolean checkCron(String cron) {
    try {
        return CronExpression.isValidExpression(cron);
    } catch (Exception e) {
        return false;
    }
}
 
Example 13
Source File: CronValidator.java    From FEBS-Cloud with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
    try {
        return CronExpression.isValidExpression(value);
    } catch (Exception e) {
        return false;
    }
}
 
Example 14
Source File: Communicate.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public String getCron() {
	if (StringUtils.isNotEmpty(this.cron) && CronExpression.isValidExpression(this.cron)) {
		return this.cron;
	} else {
		return DEFAULT_CRON;
	}
}
 
Example 15
Source File: QuartzJobServiceImpl.java    From DimpleBlog with Apache License 2.0 5 votes vote down vote up
@Override
public int insertQuartzJob(QuartzJob quartzJob) {
    if (!CronExpression.isValidExpression(quartzJob.getCronExpression())) {
        throw new CustomException("Cron表达式错误");
    }
    quartzManage.addJob(quartzJob);
    return quartzJobMapper.insertQuartzJob(quartzJob);
}
 
Example 16
Source File: ProcessPlatform.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public String getCron() {
	if (StringUtils.isNotEmpty(this.cron) && CronExpression.isValidExpression(this.cron)) {
		return this.cron;
	} else {
		return DEFAULT_CRON;
	}
}
 
Example 17
Source File: XxlJobServiceImpl.java    From zuihou-admin-boot with Apache License 2.0 4 votes vote down vote up
@Override
public ReturnT<String> add(XxlJobInfo jobInfo) {
    // valid 执行器是否存在
    XxlJobGroup group = xxlJobGroupDao.load(jobInfo.getJobGroup());
    if (group == null) {
        group = xxlJobGroupDao.getByName(jobInfo.getJobGroupName());
        if (group == null) {
            return new ReturnT<>(ReturnT.FAIL_CODE, (I18nUtil.getString("system_please_choose") + I18nUtil.getString("jobinfo_field_jobgroup")));
        }
        jobInfo.setJobGroup(group.getId());
    }


    if (JobTypeEnum.CRON.eq(jobInfo.getType())) {
        if (!CronExpression.isValidExpression(jobInfo.getJobCron())) {
            return new ReturnT<>(ReturnT.FAIL_CODE, I18nUtil.getString("jobinfo_field_cron_unvalid"));
        }
    } else {
        jobInfo.setType(JobTypeEnum.TIMES.getCode());
        //表单校验
        String msg = validate(jobInfo.getIntervalSeconds(), jobInfo.getRepeatCount(),
                jobInfo.getStartExecuteTime(), jobInfo.getEndExecuteTime());
        if (!StringUtils.isEmpty(msg)) {
            return new ReturnT<>(ReturnT.FAIL_CODE, msg);
        }
    }
    if (GlueTypeEnum.BEAN == GlueTypeEnum.match(jobInfo.getGlueType()) && StringUtils.isBlank(jobInfo.getExecutorHandler())) {
        return new ReturnT<>(ReturnT.FAIL_CODE, (I18nUtil.getString("system_please_input") + "JobHandler"));
    }

    if (StringUtils.isBlank(jobInfo.getJobDesc())) {
        jobInfo.setJobDesc("任务描述");
    }
    if (StringUtils.isBlank(jobInfo.getAuthor())) {
        jobInfo.setAuthor("admin");
    }
    if (ExecutorRouteStrategyEnum.match(jobInfo.getExecutorRouteStrategy(), null) == null) {
        jobInfo.setExecutorRouteStrategy(ExecutorRouteStrategyEnum.FIRST.name());
    }
    if (ExecutorBlockStrategyEnum.match(jobInfo.getExecutorBlockStrategy(), null) == null) {
        jobInfo.setExecutorBlockStrategy(ExecutorBlockStrategyEnum.SERIAL_EXECUTION.name());
    }
    if (GlueTypeEnum.match(jobInfo.getGlueType()) == null) {
        jobInfo.setGlueType(GlueTypeEnum.BEAN.name());
    }
    // fix "\r" in shell
    if (GlueTypeEnum.GLUE_SHELL == GlueTypeEnum.match(jobInfo.getGlueType()) && jobInfo.getGlueSource() != null) {
        jobInfo.setGlueSource(jobInfo.getGlueSource().replaceAll("\r", ""));
    }

    // ChildJobId valid
    if (StringUtils.isNotBlank(jobInfo.getChildJobId())) {
        String[] childJobIds = StringUtils.split(jobInfo.getChildJobId(), ",");
        for (String childJobIdItem : childJobIds) {
            if (StringUtils.isNotBlank(childJobIdItem) && StringUtils.isNumeric(childJobIdItem)) {
                XxlJobInfo childJobInfo = xxlJobInfoDao.loadById(Integer.valueOf(childJobIdItem));
                if (childJobInfo == null) {
                    return new ReturnT<String>(ReturnT.FAIL_CODE,
                            MessageFormat.format((I18nUtil.getString("jobinfo_field_childJobId") + "({0})" + I18nUtil.getString("system_not_found")), childJobIdItem));
                }
            } else {
                return new ReturnT<String>(ReturnT.FAIL_CODE,
                        MessageFormat.format((I18nUtil.getString("jobinfo_field_childJobId") + "({0})" + I18nUtil.getString("system_unvalid")), childJobIdItem));
            }
        }
        jobInfo.setChildJobId(StringUtils.join(childJobIds, ","));
    }


    // add in db
    xxlJobInfoDao.save(jobInfo);
    if (jobInfo.getId() < 1) {
        return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_add") + I18nUtil.getString("system_fail")));
    }

    return new ReturnT<String>(String.valueOf(jobInfo.getId()));
}
 
Example 18
Source File: XxlJobServiceImpl.java    From zuihou-admin-cloud with Apache License 2.0 4 votes vote down vote up
@Override
public ReturnT<String> update(XxlJobInfo jobInfo) {

    // valid
    if (JobTypeEnum.CRON.eq(jobInfo.getType())) {
        if (!CronExpression.isValidExpression(jobInfo.getJobCron())) {
            return new ReturnT<String>(ReturnT.FAIL_CODE, I18nUtil.getString("jobinfo_field_cron_unvalid"));
        }
    } else {
        //表单校验
        String msg = validate(jobInfo.getIntervalSeconds(), jobInfo.getRepeatCount(),
                jobInfo.getStartExecuteTime(), jobInfo.getEndExecuteTime());
        if (!StringUtils.isEmpty(msg)) {
            return new ReturnT<String>(ReturnT.FAIL_CODE, msg);
        }
    }
    if (StringUtils.isBlank(jobInfo.getJobDesc())) {
        return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("system_please_input") + I18nUtil.getString("jobinfo_field_jobdesc")));
    }
    if (StringUtils.isBlank(jobInfo.getAuthor())) {
        return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("system_please_input") + I18nUtil.getString("jobinfo_field_author")));
    }
    if (ExecutorRouteStrategyEnum.match(jobInfo.getExecutorRouteStrategy(), null) == null) {
        return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_executorRouteStrategy") + I18nUtil.getString("system_unvalid")));
    }
    if (ExecutorBlockStrategyEnum.match(jobInfo.getExecutorBlockStrategy(), null) == null) {
        return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_executorBlockStrategy") + I18nUtil.getString("system_unvalid")));
    }

    // ChildJobId valid
    if (StringUtils.isNotBlank(jobInfo.getChildJobId())) {
        String[] childJobIds = StringUtils.split(jobInfo.getChildJobId(), ",");
        for (String childJobIdItem : childJobIds) {
            if (StringUtils.isNotBlank(childJobIdItem) && StringUtils.isNumeric(childJobIdItem)) {
                XxlJobInfo childJobInfo = xxlJobInfoDao.loadById(Integer.valueOf(childJobIdItem));
                if (childJobInfo == null) {
                    return new ReturnT<String>(ReturnT.FAIL_CODE,
                            MessageFormat.format((I18nUtil.getString("jobinfo_field_childJobId") + "({0})" + I18nUtil.getString("system_not_found")), childJobIdItem));
                }
            } else {
                return new ReturnT<String>(ReturnT.FAIL_CODE,
                        MessageFormat.format((I18nUtil.getString("jobinfo_field_childJobId") + "({0})" + I18nUtil.getString("system_unvalid")), childJobIdItem));
            }
        }
        jobInfo.setChildJobId(StringUtils.join(childJobIds, ","));
    }

    // stage job info
    XxlJobInfo existsJobInfo = xxlJobInfoDao.loadById(jobInfo.getId());
    if (existsJobInfo == null) {
        return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_id") + I18nUtil.getString("system_not_found")));
    }
    //String old_cron = exists_jobInfo.getJobCron();

    existsJobInfo.setJobCron(jobInfo.getJobCron());
    existsJobInfo.setJobDesc(jobInfo.getJobDesc());
    existsJobInfo.setAuthor(jobInfo.getAuthor());
    existsJobInfo.setAlarmEmail(jobInfo.getAlarmEmail());
    existsJobInfo.setExecutorRouteStrategy(jobInfo.getExecutorRouteStrategy());
    existsJobInfo.setExecutorHandler(jobInfo.getExecutorHandler());
    existsJobInfo.setExecutorParam(jobInfo.getExecutorParam());
    existsJobInfo.setExecutorBlockStrategy(jobInfo.getExecutorBlockStrategy());
    existsJobInfo.setExecutorTimeout(jobInfo.getExecutorTimeout());
    existsJobInfo.setExecutorFailRetryCount(jobInfo.getExecutorFailRetryCount());
    existsJobInfo.setChildJobId(jobInfo.getChildJobId());
    existsJobInfo.setRepeatCount(jobInfo.getRepeatCount());
    existsJobInfo.setStartExecuteTime(jobInfo.getStartExecuteTime());
    existsJobInfo.setEndExecuteTime(jobInfo.getEndExecuteTime());
    existsJobInfo.setIntervalSeconds(jobInfo.getIntervalSeconds());
    xxlJobInfoDao.update(existsJobInfo);

    if (JobTypeEnum.TIMES.eq(jobInfo.getType())) {
        return ReturnT.SUCCESS;
    }

    // update quartz-cron if started
    String qzGroup = String.valueOf(existsJobInfo.getJobGroup());
    String qzName = String.valueOf(existsJobInfo.getId());
    try {
        XxlJobDynamicScheduler.updateJobCron(qzGroup, qzName, existsJobInfo.getJobCron());
    } catch (SchedulerException e) {
        logger.error(e.getMessage(), e);
        return ReturnT.FAIL;
    }

    return ReturnT.SUCCESS;
}
 
Example 19
Source File: XxlJobServiceImpl.java    From open-capacity-platform with Apache License 2.0 4 votes vote down vote up
@Override
public ReturnT<String> add(XxlJobInfo jobInfo) {
	// valid
	XxlJobGroup group = xxlJobGroupDao.load(jobInfo.getJobGroup());
	if (group == null) {
		return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("system_please_choose")+I18nUtil.getString("jobinfo_field_jobgroup")) );
	}
	if (!CronExpression.isValidExpression(jobInfo.getJobCron())) {
		return new ReturnT<String>(ReturnT.FAIL_CODE, I18nUtil.getString("jobinfo_field_cron_unvalid") );
	}
	if (StringUtils.isBlank(jobInfo.getJobDesc())) {
		return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("system_please_input")+I18nUtil.getString("jobinfo_field_jobdesc")) );
	}
	if (StringUtils.isBlank(jobInfo.getAuthor())) {
		return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("system_please_input")+I18nUtil.getString("jobinfo_field_author")) );
	}
	if (ExecutorRouteStrategyEnum.match(jobInfo.getExecutorRouteStrategy(), null) == null) {
		return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_executorRouteStrategy")+I18nUtil.getString("system_unvalid")) );
	}
	if (ExecutorBlockStrategyEnum.match(jobInfo.getExecutorBlockStrategy(), null) == null) {
		return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_executorBlockStrategy")+I18nUtil.getString("system_unvalid")) );
	}
	if (ExecutorFailStrategyEnum.match(jobInfo.getExecutorFailStrategy(), null) == null) {
		return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_executorFailStrategy")+I18nUtil.getString("system_unvalid")) );
	}
	if (GlueTypeEnum.match(jobInfo.getGlueType()) == null) {
		return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_gluetype")+I18nUtil.getString("system_unvalid")) );
	}
	if (GlueTypeEnum.BEAN==GlueTypeEnum.match(jobInfo.getGlueType()) && StringUtils.isBlank(jobInfo.getExecutorHandler())) {
		return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("system_please_input")+"JobHandler") );
	}

	// fix "\r" in shell
	if (GlueTypeEnum.GLUE_SHELL==GlueTypeEnum.match(jobInfo.getGlueType()) && jobInfo.getGlueSource()!=null) {
		jobInfo.setGlueSource(jobInfo.getGlueSource().replaceAll("\r", ""));
	}

	// ChildJobId valid
	if (StringUtils.isNotBlank(jobInfo.getChildJobId())) {
		String[] childJobIds = StringUtils.split(jobInfo.getChildJobId(), ",");
		for (String childJobIdItem: childJobIds) {
			if (StringUtils.isNotBlank(childJobIdItem) && StringUtils.isNumeric(childJobIdItem)) {
				XxlJobInfo childJobInfo = xxlJobInfoDao.loadById(Integer.valueOf(childJobIdItem));
				if (childJobInfo==null) {
					return new ReturnT<String>(ReturnT.FAIL_CODE,
							MessageFormat.format((I18nUtil.getString("jobinfo_field_childJobId")+"({0})"+I18nUtil.getString("system_not_found")), childJobIdItem));
				}
			} else {
				return new ReturnT<String>(ReturnT.FAIL_CODE,
						MessageFormat.format((I18nUtil.getString("jobinfo_field_childJobId")+"({0})"+I18nUtil.getString("system_unvalid")), childJobIdItem));
			}
		}
		jobInfo.setChildJobId(StringUtils.join(childJobIds, ","));
	}

	// add in db
	xxlJobInfoDao.save(jobInfo);
	if (jobInfo.getId() < 1) {
		return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_add")+I18nUtil.getString("system_fail")) );
	}

	// add in quartz
       String qz_group = String.valueOf(jobInfo.getJobGroup());
       String qz_name = String.valueOf(jobInfo.getId());
       try {
           XxlJobDynamicScheduler.addJob(qz_name, qz_group, jobInfo.getJobCron());
           //XxlJobDynamicScheduler.pauseJob(qz_name, qz_group);
           return ReturnT.SUCCESS;
       } catch (SchedulerException e) {
           logger.error(e.getMessage(), e);
           try {
               xxlJobInfoDao.delete(jobInfo.getId());
               XxlJobDynamicScheduler.removeJob(qz_name, qz_group);
           } catch (SchedulerException e1) {
               logger.error(e.getMessage(), e1);
           }
           return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_add")+I18nUtil.getString("system_fail"))+":" + e.getMessage());
       }
}
 
Example 20
Source File: CronUtils.java    From ruoyiplus with MIT License 2 votes vote down vote up
/**
 * 返回一个布尔值代表一个给定的Cron表达式的有效性
 *
 * @param cronExpression Cron表达式
 * @return boolean 表达式是否有效
 */
public static boolean isValid(String cronExpression)
{
    return CronExpression.isValidExpression(cronExpression);
}