下面列出了怎么用org.quartz.CronExpression的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 新增任务
*
* @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;
}
/**
* 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);
}
@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();
// }
}
/**
* 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;
}
}
/**
* 更新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;
}
/**
* Creates a new quartz scheduler Trigger, which can be used to
* schedule a new job by passing it into {@link io.mangoo.scheduler.Scheduler#schedule(JobDetail, Trigger) schedule}
*
* @param identity The name of the trigger
* @param groupName The trigger group name
* @param description The trigger description
* @param cron The cron expression for the trigger
*
* @return A new Trigger object
*/
public static Trigger createTrigger(String identity, String groupName, String description, String cron) {
Objects.requireNonNull(identity, Required.IDENTITY.toString());
Objects.requireNonNull(groupName, Required.GROUP_NAME.toString());
Objects.requireNonNull(cron, Required.CRON.toString());
Preconditions.checkArgument(CronExpression.isValidExpression(cron), "cron expression is invalid");
return newTrigger()
.withIdentity(identity, groupName)
.withSchedule(cronSchedule(cron))
.withDescription(description)
.build();
}
/**
* 返回下一个执行时间根据给定的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());
}
}
private static String validateSchedule(String sessionValidationSchedule) {
try {
CronExpression.validateExpression(sessionValidationSchedule);
return sessionValidationSchedule;
} catch (ParseException e) {
throw new IllegalArgumentException("Invalid session validation schedule", e);
}
}
@Override
public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
try {
return CronExpression.isValidExpression(value);
} catch (Exception e) {
return false;
}
}
@GetMapping("cron/check")
public boolean checkCron(String cron) {
try {
return CronExpression.isValidExpression(cron);
} catch (Exception e) {
return false;
}
}
@Test
public void testGetCronExpression() throws ParseException
{
// Build a list of system jobs to be scheduled.
Map<String, AbstractSystemJob> systemJobs = applicationContext.getBeansOfType(AbstractSystemJob.class);
// Validate that we located the expected number of system job.
assertEquals(7, CollectionUtils.size(systemJobs));
// Validate cron expression configured in the system for each system job.
for (Map.Entry<String, AbstractSystemJob> entry : systemJobs.entrySet())
{
// Get the name and the system job implementation.
String jobName = entry.getKey();
AbstractSystemJob systemJob = entry.getValue();
// Get the cron expression configured in the system for the job.
String cronExpressionAsText = systemJob.getCronExpression();
LOGGER.info(String.format("Testing cron expression \"%s\" specified for \"%s\" system job...", cronExpressionAsText, jobName));
// Validate the cron expression.
if (CronExpression.isValidExpression(cronExpressionAsText))
{
CronExpression cronExpression = new CronExpression(cronExpressionAsText);
LOGGER.info(String.format("Next valid time for \"%s\" cron expression after now is \"%s\".", cronExpressionAsText,
cronExpression.getNextValidTimeAfter(new Date())));
}
else
{
fail(String.format("Cron expression \"%s\" specified for \"%s\" system job is not valid.", cronExpressionAsText, jobName));
}
}
}
/**
* 返回下一个执行时间根据给定的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());
}
}
@RequestMapping("/checkCorn")
public BaseRspEntity checkCorn(@RequestParam("corn") String corn) {
BaseRspEntity resEntity = new BaseRspEntity(ConstantsHelper.RET_SUCCESS);
boolean validExpression = CronExpression.isValidExpression(corn);
resEntity.setData(validExpression);
return resEntity;
}
/**
* 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();
}
@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;
}
}
/**
* 获取时间区间内,满足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;
}
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;
}
@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");
}
@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);
}
/**
* 更新任务
*
* @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;
}
/** 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"));
}
@Override
public int insertQuartzJob(QuartzJob quartzJob) {
if (!CronExpression.isValidExpression(quartzJob.getCronExpression())) {
throw new CustomException("Cron表达式错误");
}
quartzManage.addJob(quartzJob);
return quartzJobMapper.insertQuartzJob(quartzJob);
}
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();
}
@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");
}
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();
}
@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;
}
}
/**
* 返回下一个执行时间根据给定的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());
}
}
/**
* 返回一个字符串值,表示该消息无效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();
}
}
/**
* 返回下一个执行时间根据给定的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());
}
}
/**
* 返回一个字符串值,表示该消息无效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();
}
}