Search in sources :

Example 1 with ForecastCronResult

use of com.vip.saturn.job.console.domain.ForecastCronResult in project Saturn by vipshop.

the class UtilsServiceImpl method checkAndForecastCron.

@Override
public ForecastCronResult checkAndForecastCron(final String timeZone, final String cron) throws SaturnJobConsoleException {
    if (StringUtils.isBlank(timeZone)) {
        throw new SaturnJobConsoleException("timeZone不能为空");
    }
    if (StringUtils.isBlank(cron)) {
        throw new SaturnJobConsoleException("cron不能为空");
    }
    String timeZoneTrim = timeZone.trim();
    String cronTrim = cron.trim();
    if (!SaturnConstants.TIME_ZONE_IDS.contains(timeZoneTrim)) {
        throw new SaturnJobConsoleException(String.format("timeZone(%s)无效", timeZoneTrim));
    }
    TimeZone tz = TimeZone.getTimeZone(timeZoneTrim);
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    dateFormat.setTimeZone(tz);
    CronExpression cronExpression = null;
    try {
        cronExpression = new CronExpression(cronTrim);
    } catch (ParseException e) {
        throw new SaturnJobConsoleException(String.format("cron(%s)格式错误:%s", cronTrim, e.getMessage()));
    }
    cronExpression.setTimeZone(tz);
    ForecastCronResult forecastCronResult = new ForecastCronResult();
    forecastCronResult.setTimeZone(timeZoneTrim);
    forecastCronResult.setCron(cronTrim);
    forecastCronResult.setNextFireTimes(new ArrayList<String>());
    Date now = new Date();
    for (int i = 0; i < 10; i++) {
        Date next = cronExpression.getNextValidTimeAfter(now);
        if (next != null) {
            forecastCronResult.getNextFireTimes().add(dateFormat.format(next));
            now = next;
        }
    }
    if (forecastCronResult.getNextFireTimes().isEmpty()) {
        throw new SaturnJobConsoleException(String.format("cron(%s)可能描述的是一个过去的时间,将不会被执行", cronTrim));
    }
    return forecastCronResult;
}
Also used : TimeZone(java.util.TimeZone) SaturnJobConsoleException(com.vip.saturn.job.console.exception.SaturnJobConsoleException) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) ForecastCronResult(com.vip.saturn.job.console.domain.ForecastCronResult) CronExpression(com.vip.saturn.job.console.utils.CronExpression) ParseException(java.text.ParseException) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date)

Aggregations

ForecastCronResult (com.vip.saturn.job.console.domain.ForecastCronResult)1 SaturnJobConsoleException (com.vip.saturn.job.console.exception.SaturnJobConsoleException)1 CronExpression (com.vip.saturn.job.console.utils.CronExpression)1 DateFormat (java.text.DateFormat)1 ParseException (java.text.ParseException)1 SimpleDateFormat (java.text.SimpleDateFormat)1 Date (java.util.Date)1 TimeZone (java.util.TimeZone)1