org.quartz.CronExpression Java Examples
The following examples show how to use
org.quartz.CronExpression.
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: JobService.java From FlyCms with MIT License | 6 votes |
/** * 新增任务 * * @param job */ public DataVo insertJob(Job job){ DataVo data = DataVo.failure("操作失败"); if (!CronExpression.isValidExpression(job.getCronExpression())){ return data=DataVo.failure("cron表达式格式错误!"); } if(this.checkJobByMethodName(job.getBeanName(),job.getMethodName())){ return data=DataVo.failure("该任务已存在!"); } SnowFlake snowFlake = new SnowFlake(2, 3); job.setId(snowFlake.nextId()); job.setCreateTime(new Date()); int totalCount=jobDao.insertJob(job); if(totalCount > 0){ if ("1".equals(job.getStatus())) { ScheduleUtils.createScheduleJob(scheduler, job); } data = DataVo.success("添加成功", DataVo.NOOP); }else{ data=DataVo.failure("未知错误!"); } return data; }
Example #2
Source File: QuartzScheduleFactory.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
/** * Cron schedule support using {@link CronExpression} validation. */ @Override public Cron cron(final Date startAt, final String cronExpression) { checkNotNull(startAt); checkArgument(!Strings2.isBlank(cronExpression), "Empty Cron expression"); // checking with regular-expression checkArgument(CRON_PATTERN.matcher(cronExpression).matches(), "Invalid Cron expression: %s", cronExpression); // and implementation for better coverage, as the following misses some invalid syntax try { CronExpression.validateExpression(cronExpression); } catch (ParseException e) { throw new IllegalArgumentException("Invalid Cron expression: '" + cronExpression + "': " + e.getMessage(), e); } return new Cron(startAt, cronExpression); }
Example #3
Source File: Schedule.java From webcurator with Apache License 2.0 | 6 votes |
/** * Retrieves the next execution time based on the schedule and * the supplied date. * @param after The date to get the next invocation after. * @return The next execution time. */ public Date getNextExecutionDate(Date after) { try { CronExpression expression = new CronExpression(this.getCronPattern()); Date next = expression.getNextValidTimeAfter(DateUtils.latestDate(after, new Date())); if(next == null) { return null; } else if(endDate != null && next.after(endDate)) { return null; } else { return next; } } catch(ParseException ex) { System.out.println(" Encountered ParseException for cron expression: " + this.getCronPattern() + " in schedule: " + this.getOid()); return null; } }
Example #4
Source File: AbstractSchedulingContentCacheController.java From arctic-sea with Apache License 2.0 | 6 votes |
@Setting(ScheduledContentCacheControllerSettings.CAPABILITIES_CACHE_UPDATE) public void setCronExpression(String cronExpression) { Validation.notNullOrEmpty("Cron expression for cache update", cronExpression); try { DateTime now = DateTime.now(); Date next = new CronExpression(cronExpression).getNextInvalidTimeAfter(DateTime.now().toDate()); setUpdateInterval(DateTimeHelper.getMinutesSince(now, new DateTime(next))); } catch (ParseException e) { throw new ConfigurationError(String.format("The defined cron expression '%s' is invalid!", cronExpression), e); } // for later usage! // if (this.cronExpression == null) { // this.cronExpression = cronExpression; // reschedule(); // } else if (!this.cronExpression.equalsIgnoreCase(cronExpression)) { // this.cronExpression = cronExpression; // reschedule(); // } }
Example #5
Source File: QssService.java From seed with Apache License 2.0 | 6 votes |
/** * 更新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 #6
Source File: StandardReportingTaskDAO.java From localization_nifi with Apache License 2.0 | 5 votes |
private List<String> validateProposedConfiguration(final ReportingTaskNode reportingTask, final ReportingTaskDTO reportingTaskDTO) { final List<String> validationErrors = new ArrayList<>(); // get the current scheduling strategy SchedulingStrategy schedulingStrategy = reportingTask.getSchedulingStrategy(); // validate the new scheduling strategy if appropriate if (isNotNull(reportingTaskDTO.getSchedulingStrategy())) { try { // this will be the new scheduling strategy so use it schedulingStrategy = SchedulingStrategy.valueOf(reportingTaskDTO.getSchedulingStrategy()); } catch (IllegalArgumentException iae) { validationErrors.add(String.format("Scheduling strategy: Value must be one of [%s]", StringUtils.join(SchedulingStrategy.values(), ", "))); } } // validate the scheduling period based on the scheduling strategy if (isNotNull(reportingTaskDTO.getSchedulingPeriod())) { switch (schedulingStrategy) { case TIMER_DRIVEN: final Matcher schedulingMatcher = FormatUtils.TIME_DURATION_PATTERN.matcher(reportingTaskDTO.getSchedulingPeriod()); if (!schedulingMatcher.matches()) { validationErrors.add("Scheduling period is not a valid time duration (ie 30 sec, 5 min)"); } break; case CRON_DRIVEN: try { new CronExpression(reportingTaskDTO.getSchedulingPeriod()); } catch (final ParseException pe) { throw new IllegalArgumentException(String.format("Scheduling Period '%s' is not a valid cron expression: %s", reportingTaskDTO.getSchedulingPeriod(), pe.getMessage())); } catch (final Exception e) { throw new IllegalArgumentException("Scheduling Period is not a valid cron expression: " + reportingTaskDTO.getSchedulingPeriod()); } break; } } return validationErrors; }
Example #7
Source File: VerifyController.java From opencron with Apache License 2.0 | 5 votes |
@RequestMapping("/exp") public void validateCronExp(Integer cronType, String cronExp, HttpServletResponse response) { boolean pass = false; if (cronType == 0) pass = SchedulingPattern.validate(cronExp); if (cronType == 1) pass = CronExpression.isValidExpression(cronExp); WebUtils.writeHtml(response, pass ? "success" : "failure"); }
Example #8
Source File: QuartzJobServiceImpl.java From eladmin with Apache License 2.0 | 5 votes |
@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 #9
Source File: ProcessPlatform.java From o2oa with GNU Affero General Public License v3.0 | 5 votes |
public String getCron() { if (StringUtils.isNotEmpty(this.cron) && CronExpression.isValidExpression(this.cron)) { return this.cron; } else { return DEFAULT_CRON; } }
Example #10
Source File: ProcessPlatform.java From o2oa with GNU Affero General Public License v3.0 | 5 votes |
public String getCron() { if (StringUtils.isNotEmpty(this.cron) && CronExpression.isValidExpression(this.cron)) { return this.cron; } else { return DEFAULT_CRON; } }
Example #11
Source File: CronUtils.java From RuoYi-Vue with MIT License | 5 votes |
/** * 返回下一个执行时间根据给定的Cron表达式 * * @param cronExpression Cron表达式 * @return Date 下次Cron表达式执行时间 */ public static Date getNextExecution(String cronExpression) { try { CronExpression cron = new CronExpression(cronExpression); return cron.getNextValidTimeAfter(new Date(System.currentTimeMillis())); } catch (ParseException e) { throw new IllegalArgumentException(e.getMessage()); } }
Example #12
Source File: JobService.java From FlyCms with MIT License | 5 votes |
/** * 更新任务 * * @param job */ public DataVo updateJobById(Job job){ DataVo data = DataVo.failure("操作失败"); Job oldJob = this.findJobById(job.getId()); if(oldJob==null){ return data = DataVo.failure("该任务不存在"); } if (!CronExpression.isValidExpression(job.getCronExpression())){ return data=DataVo.failure("cron表达式格式错误!"); } if(this.checkJobByMethodNameNotId(job.getBeanName(),job.getMethodName(),job.getId())){ return data=DataVo.failure("已存在,不能同时存在两个以上任务!"); } job.setCreateTime(new Date()); int totalCount=jobDao.updateJobById(job); if(totalCount > 0){ CronTrigger trigger = ScheduleUtils.getCronTrigger(scheduler, job.getId()); if (trigger == null) { ScheduleUtils.createScheduleJob(scheduler, job); }else{ ScheduleUtils.updateScheduleJob(scheduler, job); } data = DataVo.success("已更新成功!", DataVo.NOOP); }else{ data=DataVo.failure("未知错误!"); } return data; }
Example #13
Source File: JobController.java From FEBS-Cloud with Apache License 2.0 | 5 votes |
@GetMapping("cron/check") public boolean checkCron(String cron) { try { return CronExpression.isValidExpression(cron); } catch (Exception e) { return false; } }
Example #14
Source File: ExecutorImpl.java From DataHubSystem with GNU Affero General Public License v3.0 | 5 votes |
/** Constructor. */ public CronSchedule (String cron_string) throws ParseException { Objects.requireNonNull (cron_string); this.cronString = cron_string; this.cronExpression = new CronExpression (cron_string); this.cronExpression.setTimeZone (TimeZone.getTimeZone ("UTC")); }
Example #15
Source File: EditScheduleController.java From webcurator with Apache License 2.0 | 5 votes |
protected ModelAndView handleView(HttpServletRequest request, HttpServletResponse response, Object comm, BindException errors) throws Exception { TargetSchedulesCommand command = (TargetSchedulesCommand) comm; Schedule aSchedule = (Schedule) getEditorContext(request).getObject(Schedule.class, command.getSelectedItem()); TargetSchedulesCommand newCommand = TargetSchedulesCommand.buildFromModel(aSchedule); List<Date> testResults = new LinkedList<Date>(); ModelAndView mav = getEditView(request, response, newCommand, errors); mav.addObject("testResults", testResults); mav.addObject("viewMode", new Boolean(true)); newCommand.setHeatMap(buildHeatMap()); newCommand.setHeatMapThresholds(buildHeatMapThresholds()); if(newCommand.getScheduleType() < 0) { mav.addObject("monthOptions", getMonthOptionsByType(newCommand.getScheduleType())); } try { CronExpression expr = new CronExpression(aSchedule.getCronPattern()); Date d = DateUtils.latestDate(new Date(), newCommand.getStartDate()); Date nextDate = null; for(int i = 0; i<10; i++) { nextDate = expr.getNextValidTimeAfter(d); if(nextDate == null || newCommand.getEndDate() != null && nextDate.after(newCommand.getEndDate())) { break; } testResults.add(nextDate); d = nextDate; } } catch(ParseException ex) { ex.printStackTrace(); } return mav; }
Example #16
Source File: ProcessPlatform.java From o2oa with GNU Affero General Public License v3.0 | 5 votes |
public String getCron() { if (StringUtils.isNotEmpty(this.cron) && CronExpression.isValidExpression(this.cron)) { return this.cron; } else { return DEFAULT_CRON; } }
Example #17
Source File: EditScheduleController.java From webcurator with Apache License 2.0 | 5 votes |
protected ModelAndView handleTest(HttpServletRequest request, HttpServletResponse response, Object comm, BindException errors) throws Exception { TargetSchedulesCommand command = (TargetSchedulesCommand) comm; if(errors.hasErrors()) { return getEditView(request, response, comm, errors); } else { List<Date> testResults = new LinkedList<Date>(); ModelAndView mav = getEditView(request, response, comm, errors); mav.addObject("testResults", testResults); try { CronExpression expr = new CronExpression(command.getCronExpression()); Date d = DateUtils.latestDate(new Date(), command.getStartDate()); Date nextDate = null; for(int i = 0; i<10; i++) { nextDate = expr.getNextValidTimeAfter(d); if(nextDate == null || command.getEndDate() != null && nextDate.after(command.getEndDate())) { break; } testResults.add(nextDate); d = nextDate; } } catch(ParseException ex) { ex.printStackTrace(); } return mav; } }
Example #18
Source File: QuartzJobServiceImpl.java From DimpleBlog with Apache License 2.0 | 5 votes |
@Override public int insertQuartzJob(QuartzJob quartzJob) { if (!CronExpression.isValidExpression(quartzJob.getCronExpression())) { throw new CustomException("Cron表达式错误"); } quartzManage.addJob(quartzJob); return quartzJobMapper.insertQuartzJob(quartzJob); }
Example #19
Source File: QuartzUtils.java From liteflow with Apache License 2.0 | 5 votes |
/** * 获取时间区间内,满足crontab表达式的时间 * @param crontab * @param startTime * @param endTime * @return */ public static List<Date> getRunDateTimes(String crontab, Date startTime, Date endTime){ Preconditions.checkArgument(startTime != null, "startTime is null"); Preconditions.checkArgument(endTime != null, "endTime is null"); List<Date> dateTimes = Lists.newArrayList(); try { CronExpression cronExpression = new CronExpression(crontab); /** * 由于开始时间可能与第一次触发时间相同而导致拿不到第一个时间 * 所以,起始时间较少1ms */ DateTime startDateTime = new DateTime(startTime).minusMillis(1); Date runtime = startDateTime.toDate(); do{ runtime = cronExpression.getNextValidTimeAfter(runtime); if(runtime.before(endTime)){ dateTimes.add(runtime); } }while (runtime.before(endTime)); } catch (Exception e) { throw new IllegalArgumentException(crontab + " is invalid"); } return dateTimes; }
Example #20
Source File: AbstractCronTask.java From aion-germany with GNU General Public License v3.0 | 5 votes |
public AbstractCronTask(String cronExpression) throws ParseException { if (cronExpression == null) { throw new NullPointerException("cronExpressionString"); } cronExpressionString = cronExpression; ServerVariablesDAO dao = DAOManager.getDAO(ServerVariablesDAO.class); runTime = dao.load(getServerTimeVariable()); preInit(); runExpression = new CronExpression(cronExpressionString); Date nextDate = runExpression.getTimeAfter(new Date()); Date nextAfterDate = runExpression.getTimeAfter(nextDate); period = nextAfterDate.getTime() - nextDate.getTime(); postInit(); if (getRunDelay() == 0) { if (canRunOnInit()) { ThreadPoolManager.getInstance().schedule(this, 0); } else { saveNextRunTime(); } } scheduleNextRun(); }
Example #21
Source File: HousingBidService.java From aion-germany with GNU General Public License v3.0 | 5 votes |
@Override protected void postInit() { try { registerDateExpr = new CronExpression(registerEndExpression); } catch (ParseException e) { log.error("[HousingBidService] Error with CronExpression: " + e.getMessage()); } ServerVariablesDAO dao = DAOManager.getDAO(ServerVariablesDAO.class); timeProlonged = dao.load("auctionProlonged"); }
Example #22
Source File: HRCronTriggerRunner.java From NewsRecommendSystem with MIT License | 5 votes |
public void task(List<Long> users,String cronExpression) throws SchedulerException { // Initiate a Schedule Factory SchedulerFactory schedulerFactory = new StdSchedulerFactory(); // Retrieve a scheduler from schedule factory Scheduler scheduler = schedulerFactory.getScheduler(); // Initiate JobDetail with job name, job group, and executable job class JobDetailImpl jobDetailImpl = new JobDetailImpl(); jobDetailImpl.setJobClass(HRJob.class); jobDetailImpl.setKey(new JobKey("HRJob1")); jobDetailImpl.getJobDataMap().put("users",users); // Initiate CronTrigger with its name and group name CronTriggerImpl cronTriggerImpl = new CronTriggerImpl(); cronTriggerImpl.setName("HRCronTrigger1"); try { // setup CronExpression CronExpression cexp = new CronExpression(cronExpression); // Assign the CronExpression to CronTrigger cronTriggerImpl.setCronExpression(cexp); } catch (Exception e) { e.printStackTrace(); } // schedule a job with JobDetail and Trigger scheduler.scheduleJob(jobDetailImpl, cronTriggerImpl); // start the scheduler scheduler.start(); }
Example #23
Source File: XxlJobServiceImpl.java From zuihou-admin-cloud with Apache License 2.0 | 5 votes |
@Override public ReturnT<String> start(Integer id) { XxlJobInfo xxlJobInfo = xxlJobInfoDao.loadById(id); if (JobTypeEnum.CRON.eq(xxlJobInfo.getType())) { if (!CronExpression.isValidExpression(xxlJobInfo.getJobCron())) { return new ReturnT<String>(ReturnT.FAIL_CODE, I18nUtil.getString("jobinfo_field_cron_unvalid")); } } else { //表单校验 String msg = validate(xxlJobInfo.getIntervalSeconds(), xxlJobInfo.getRepeatCount(), xxlJobInfo.getStartExecuteTime(), xxlJobInfo.getEndExecuteTime()); if (!StringUtils.isEmpty(msg)) { return new ReturnT<String>(ReturnT.FAIL_CODE, msg); } } String group = String.valueOf(xxlJobInfo.getJobGroup()); String name = String.valueOf(xxlJobInfo.getId()); String cronExpression = xxlJobInfo.getJobCron(); boolean ret = false; try { //判断定时类型 if (JobTypeEnum.CRON.eq(xxlJobInfo.getType())) { ret = XxlJobDynamicScheduler.addJob(name, group, cronExpression); } else { /*if (!DateUtil.isMatch(xxlJobInfo.get())) { return new ReturnT<>(ReturnT.START_JOB_FAI, "触发时间不能小于当前时间."); }*/ ret = XxlJobDynamicScheduler.addJob(name, group, xxlJobInfo.getStartExecuteTime(), xxlJobInfo.getEndExecuteTime(), xxlJobInfo.getIntervalSeconds(), xxlJobInfo.getRepeatCount()); } return ret ? ReturnT.SUCCESS : ReturnT.FAIL; } catch (SchedulerException e) { logger.error(e.getMessage(), e); return ReturnT.FAIL; } }
Example #24
Source File: JobScheduler.java From molgenis with GNU Lesser General Public License v3.0 | 5 votes |
/** * 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 #25
Source File: StandardReportingTaskDAO.java From nifi with Apache License 2.0 | 5 votes |
private List<String> validateProposedConfiguration(final ReportingTaskNode reportingTask, final ReportingTaskDTO reportingTaskDTO) { final List<String> validationErrors = new ArrayList<>(); // get the current scheduling strategy SchedulingStrategy schedulingStrategy = reportingTask.getSchedulingStrategy(); // validate the new scheduling strategy if appropriate if (isNotNull(reportingTaskDTO.getSchedulingStrategy())) { try { // this will be the new scheduling strategy so use it schedulingStrategy = SchedulingStrategy.valueOf(reportingTaskDTO.getSchedulingStrategy()); } catch (IllegalArgumentException iae) { validationErrors.add(String.format("Scheduling strategy: Value must be one of [%s]", StringUtils.join(SchedulingStrategy.values(), ", "))); } } // validate the scheduling period based on the scheduling strategy if (isNotNull(reportingTaskDTO.getSchedulingPeriod())) { switch (schedulingStrategy) { case TIMER_DRIVEN: final Matcher schedulingMatcher = FormatUtils.TIME_DURATION_PATTERN.matcher(reportingTaskDTO.getSchedulingPeriod()); if (!schedulingMatcher.matches()) { validationErrors.add("Scheduling period is not a valid time duration (ie 30 sec, 5 min)"); } break; case CRON_DRIVEN: try { new CronExpression(reportingTaskDTO.getSchedulingPeriod()); } catch (final ParseException pe) { throw new IllegalArgumentException(String.format("Scheduling Period '%s' is not a valid cron expression: %s", reportingTaskDTO.getSchedulingPeriod(), pe.getMessage())); } catch (final Exception e) { throw new IllegalArgumentException("Scheduling Period is not a valid cron expression: " + reportingTaskDTO.getSchedulingPeriod()); } break; } } return validationErrors; }
Example #26
Source File: CronUtils.java From RuoYi with Apache License 2.0 | 5 votes |
/** * 返回下一个执行时间根据给定的Cron表达式 * * @param cronExpression Cron表达式 * @return Date 下次Cron表达式执行时间 */ public static Date getNextExecution(String cronExpression) { try { CronExpression cron = new CronExpression(cronExpression); return cron.getNextValidTimeAfter(new Date(System.currentTimeMillis())); } catch (ParseException e) { throw new IllegalArgumentException(e.getMessage()); } }
Example #27
Source File: CronUtils.java From albedo with GNU Lesser General Public License v3.0 | 5 votes |
/** * 返回下一个执行时间根据给定的Cron表达式 * * @param cronExpression Cron表达式 * @return Date 下次Cron表达式执行时间 */ public static Date getNextExecution(String cronExpression) { try { CronExpression cron = new CronExpression(cronExpression); return cron.getNextValidTimeAfter(new Date(System.currentTimeMillis())); } catch (ParseException e) { throw new IllegalArgumentException(e.getMessage()); } }
Example #28
Source File: CronUtils.java From albedo with GNU Lesser General Public License v3.0 | 5 votes |
/** * 返回一个字符串值,表示该消息无效Cron表达式给出有效性 * * @param cronExpression Cron表达式 * @return String 无效时返回表达式错误描述,如果有效返回null */ public static String getInvalidMessage(String cronExpression) { try { new CronExpression(cronExpression); return null; } catch (ParseException pe) { return pe.getMessage(); } }
Example #29
Source File: CronUtils.java From LuckyFrameWeb with GNU Affero General Public License v3.0 | 5 votes |
/** * 返回一个字符串值,表示该消息无效Cron表达式给出有效性 * * @param cronExpression Cron表达式 * @return String 无效时返回表达式错误描述,如果有效返回null */ public static String getInvalidMessage(String cronExpression) { try { new CronExpression(cronExpression); return null; } catch (ParseException pe) { return pe.getMessage(); } }
Example #30
Source File: CronUtils.java From LuckyFrameWeb with GNU Affero General Public License v3.0 | 5 votes |
/** * 返回下一个执行时间根据给定的Cron表达式 * * @param cronExpression Cron表达式 * @return Date 下次Cron表达式执行时间 */ public static Date getNextExecution(String cronExpression) { try { CronExpression cron = new CronExpression(cronExpression); return cron.getNextValidTimeAfter(new Date(System.currentTimeMillis())); } catch (ParseException e) { throw new IllegalArgumentException(e.getMessage()); } }