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

The following examples show how to use org.quartz.CronExpression#getNextValidTimeAfter() . 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: ConfigScheduler.java    From alfresco-data-model with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * This method should only be called once in production on startup generally from Spring afterPropertiesSet methods.
 * In testing it is allowed to call this method multiple times, but in that case it is recommended to pass in a
 * null cronExpression (or a cronExpression such as a date in the past) so the scheduler is not started. If this is
 * done, the config is still read, but before the method returns.
 */
public void run(boolean enabled, Log log, CronExpression cronExpression, CronExpression initialAndOnErrorCronExpression)
{
    clearPreviousSchedule();
    clearData();
    if (enabled)
    {
        this.log = log == null ? ConfigScheduler.defaultLog : log;
        Date now = new Date();
        if (cronExpression != null &&
            initialAndOnErrorCronExpression != null &&
            cronExpression.getNextValidTimeAfter(now) != null &&
            initialAndOnErrorCronExpression.getNextValidTimeAfter(now) != null)
        {
            this.cronExpression = cronExpression;
            this.initialAndOnErrorCronExpression = initialAndOnErrorCronExpression;
            schedule();
        }
        else
        {
            readConfigAndReplace(false);
        }
    }
}
 
Example 2
Source File: Schedule.java    From webcurator with Apache License 2.0 6 votes vote down vote up
/**
 * 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 3
Source File: Seqs.java    From LazySeq with Apache License 2.0 5 votes vote down vote up
public static LazySeq<Date> cronFireTimes(CronExpression expr, Date after) {
	final Date nextFireTime = expr.getNextValidTimeAfter(after);
	if (nextFireTime == null) {
		return empty();
	} else {
		return cons(nextFireTime, cronFireTimes(expr, nextFireTime));
	}
}
 
Example 4
Source File: CronUtils.java    From RuoYi-Vue with MIT License 5 votes vote down vote up
/**
 * 返回下一个执行时间根据给定的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 5
Source File: CronUtils.java    From ruoyiplus with MIT License 5 votes vote down vote up
/**
 * 返回下一个执行时间根据给定的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 6
Source File: QuartzUtils.java    From liteflow with Apache License 2.0 5 votes vote down vote up
/**
 * 获取时间区间内,满足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 7
Source File: CronUtils.java    From RuoYi with Apache License 2.0 5 votes vote down vote up
/**
 * 返回下一个执行时间根据给定的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 8
Source File: CronUtils.java    From LuckyFrameWeb with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 返回下一个执行时间根据给定的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 9
Source File: CronUtils.java    From albedo with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 返回下一个执行时间根据给定的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 10
Source File: CronUtils.java    From supplierShop with MIT License 5 votes vote down vote up
/**
 * 返回下一个执行时间根据给定的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 11
Source File: EditScheduleController.java    From webcurator with Apache License 2.0 5 votes vote down vote up
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 12
Source File: EditScheduleController.java    From webcurator with Apache License 2.0 5 votes vote down vote up
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 13
Source File: CronTools.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
public static Date next(String expression, Date lastEndDate) throws Exception {
	CronExpression cron = new CronExpression(expression);
	return cron.getNextValidTimeAfter(lastEndDate == null ? DateTools.parse("2018-01-01 00:00:00") : lastEndDate);
}
 
Example 14
Source File: SingularityJobPoller.java    From Singularity with Apache License 2.0 4 votes vote down vote up
private Optional<Long> getExpectedRuntime(
  SingularityRequest request,
  SingularityTaskId taskId
) {
  if (request.getScheduledExpectedRuntimeMillis().isPresent()) {
    return request.getScheduledExpectedRuntimeMillis();
  } else {
    final Optional<SingularityDeployStatistics> deployStatistics = deployManager.getDeployStatistics(
      taskId.getRequestId(),
      taskId.getDeployId()
    );

    if (
      deployStatistics.isPresent() &&
      deployStatistics.get().getAverageRuntimeMillis().isPresent()
    ) {
      return deployStatistics.get().getAverageRuntimeMillis();
    }

    String scheduleExpression = request.getScheduleTypeSafe() == ScheduleType.RFC5545
      ? request.getSchedule().get()
      : request.getQuartzScheduleSafe();
    Date nextRunAtDate;

    try {
      if (request.getScheduleTypeSafe() == ScheduleType.RFC5545) {
        final RFC5545Schedule rfc5545Schedule = new RFC5545Schedule(scheduleExpression);
        nextRunAtDate = rfc5545Schedule.getNextValidTime();
      } else {
        final CronExpression cronExpression = new CronExpression(scheduleExpression);
        final Date startDate = new Date(taskId.getStartedAt());
        nextRunAtDate = cronExpression.getNextValidTimeAfter(startDate);
      }

      if (nextRunAtDate == null) {
        String msg = String.format(
          "No next run date found for %s (%s)",
          taskId,
          scheduleExpression
        );
        LOG.warn(msg);
        exceptionNotifier.notify(msg, ImmutableMap.of("taskId", taskId.toString()));
        return Optional.empty();
      }
    } catch (ParseException | InvalidRecurrenceRuleException e) {
      LOG.warn(
        "Unable to parse schedule of type {} for expression {} (taskId: {}, err: {})",
        request.getScheduleTypeSafe(),
        scheduleExpression,
        taskId,
        e
      );
      exceptionNotifier.notify(
        String.format("Unable to parse schedule (%s)", e.getMessage()),
        e,
        ImmutableMap.of(
          "taskId",
          taskId.toString(),
          "scheduleExpression",
          scheduleExpression,
          "scheduleType",
          request.getScheduleTypeSafe().toString()
        )
      );
      return Optional.empty();
    }

    return Optional.of(nextRunAtDate.getTime() - taskId.getStartedAt());
  }
}
 
Example 15
Source File: TargetSchedulesValidator.java    From webcurator with Apache License 2.0 4 votes vote down vote up
private void validateCronExpression(Object aCommand, Errors aErrors) {
	TargetSchedulesCommand command = (TargetSchedulesCommand) aCommand;
	boolean hasErrors = false;
	
	if(command.getScheduleType() > Schedule.CUSTOM_SCHEDULE) {
		return;
	}
	
	// Step one - make sure all fields have been provided.
	
	// If time is null, we need minutes and hours.
	if(command.getScheduleType() == 0) { 
		ValidationUtils.rejectIfEmptyOrWhitespace(aErrors, "minutes", "required", getObjectArrayForLabel(TargetSchedulesCommand.PARAM_MINUTES), "Minutes is a required field");
		ValidationUtils.rejectIfEmptyOrWhitespace(aErrors, "hours", "required", getObjectArrayForLabel(TargetSchedulesCommand.PARAM_HOURS), "Hours is a required field");
	}
	
	if(command.getScheduleType() < 0) { 
		if(command.getTime() == null) { 
			aErrors.rejectValue("time", "required", getObjectArrayForLabel(TargetSchedulesCommand.PARAM_TIME), "Time is a required field");
		}
	}

	ValidationUtils.rejectIfEmptyOrWhitespace(aErrors, "daysOfWeek", "required", getObjectArrayForLabel(TargetSchedulesCommand.PARAM_DAYS_OF_WEEK), "Days of Week is a required field");
	ValidationUtils.rejectIfEmptyOrWhitespace(aErrors, "daysOfMonth", "required", getObjectArrayForLabel(TargetSchedulesCommand.PARAM_DAYS_OF_MONTH), "Days of Month is a required field");
	ValidationUtils.rejectIfEmptyOrWhitespace(aErrors, "months", "required", getObjectArrayForLabel(TargetSchedulesCommand.PARAM_MONTHS), "Months is a required field");
	ValidationUtils.rejectIfEmptyOrWhitespace(aErrors, "years", "required", getObjectArrayForLabel(TargetSchedulesCommand.PARAM_YEARS), "Years is a required field");
	
	// If there are missing fields, there is no point doing any further
	// validation.
	if(aErrors.hasErrors()) {
		return;
	}
	
	// If time is not provided, then checks hours and minutes.
	if(command.getScheduleType() == 0) { 
		// Validate Minute Component
		if(!isValidMinuteComponent(command.getMinutes())) {
			aErrors.reject("cron.badMinutes", new Object[] {}, "Illegal minutes string");
			hasErrors = true;
		}
		
		// Validate Hours Component
		if(!isValidMinuteComponent(command.getHours())) {
			aErrors.reject("cron.badHours", new Object[] {}, "Illegal hours string");
			hasErrors = true;
		}
	}
	
	// Validate Days of Week Component
	if(!isValidDaysOfWeekComponent(command.getDaysOfWeek())) {
		aErrors.reject("cron.badDaysOfWeek", new Object[] {}, "Illegal Days of Week string");
		hasErrors = true;
	}
	
	// Validate Days of Month Component
	if(!isValidDaysOfMonthComponent(command.getDaysOfMonth())) {
		aErrors.reject("cron.badDaysOfMonth", new Object[] {}, "Illegal Days of Month string");
		hasErrors = true;
	}		
	
	// Validate Months Component
	if(!isValidMonthsComponent(command.getMonths())) {
		aErrors.reject("cron.badMonths", new Object[] {}, "Illegal Month string");
		hasErrors = true;
	}		
	
	// Validate Years Component
	if(!isValidYearsComponent(command.getYears())) {
		aErrors.reject("cron.badYears", new Object[] {}, "Illegal Years string");
		hasErrors = true;
	}	
	
	if( !"?".equals(command.getDaysOfMonth()) &&
		!"?".equals(command.getDaysOfWeek())) {
		aErrors.reject("cron.unsupported.daysofmonthweek");
		hasErrors = true;
	}
	
	// Run the CronExpression parser to see if there is anything we haven't
	// managed to catch.
	if(!hasErrors) {
		try {
			CronExpression cex = new CronExpression(command.getCronExpression());
			if(cex.getNextValidTimeAfter(new Date()) == null ) {
				aErrors.reject("cron.noFutureInstances");
			}
		}
		catch(ParseException ex) {
			aErrors.reject("parse.error", new Object[] { ex.getMessage() }, "Unknown Error");
		}
	}
}
 
Example 16
Source File: DateTools.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
public static Date cron(String expression, Date date) throws Exception {
	CronExpression exp = new CronExpression(expression);
	return exp.getNextValidTimeAfter(date);
}
 
Example 17
Source File: CronTools.java    From youkefu with Apache License 2.0 3 votes vote down vote up
/**
 * 
 * @param crontabExp
 * @return
 * @throws ParseException
 */

public static Date getFinalFireTime(String crontabExp , Date date) throws ParseException{
	CronExpression expression = new CronExpression(crontabExp) ;
	return expression.getNextValidTimeAfter(date!=null ? date:new Date());
	
}