本文整理汇总了Java中org.quartz.CronExpression类的典型用法代码示例。如果您正苦于以下问题:Java CronExpression类的具体用法?Java CronExpression怎么用?Java CronExpression使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
CronExpression类属于org.quartz包,在下文中一共展示了CronExpression类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: isCronIntervalLessThanMinimum
import org.quartz.CronExpression; //导入依赖的package包/类
/**
* Checks if the given cron expression interval is less or equals to a certain minimum.
*
* @param cronExpression the cron expression to check
*/
public static boolean isCronIntervalLessThanMinimum(String cronExpression) {
try {
// If input is empty or invalid simply return false as default
if (StringUtils.isBlank(cronExpression) || !isValid(cronExpression)) {
return false;
}
CronExpression cron = new CronExpression(cronExpression);
final Date firstExecution = cron.getNextValidTimeAfter(new Date(System.currentTimeMillis()));
final Date secondExecution = cron.getNextValidTimeAfter(firstExecution);
Minutes intervalMinutes = Minutes.minutesBetween(new DateTime(firstExecution),
new DateTime(secondExecution));
return !intervalMinutes.isGreaterThan(MINIMUM_ALLOWED_MINUTES);
} catch (ParseException e) {
throw new IllegalArgumentException(e.getMessage());
}
}
示例2: getNextExecutionDate
import org.quartz.CronExpression; //导入依赖的package包/类
/**
* 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;
}
}
示例3: testSchedule
import org.quartz.CronExpression; //导入依赖的package包/类
@Test
public void testSchedule() throws Exception{
System.out.println("schedule");
String jobId = "testSchedule_jobId";
CronExpression cronTrigger = new CronExpression("1/1 * * ? * *");
// ZoneId zoneId = ZoneId.of("UTC");
final ConcurrentLinkedDeque<Integer> invocations = new ConcurrentLinkedDeque<>();
ScheduledJobExecutor jobExec = new ScheduledJobExecutor(){
@Override
public void execute(Map<String, Object> parameters) {
log.info("Test Task executed");
invocations.add(1);
}
};
try{
instance.schedule(jobId, cronTrigger, jobExec);
Thread.sleep(2000l);
assertTrue( invocations.size() > 0 );
}finally{
instance.unSchedule(jobId);
}
}
示例4: checkAndSaveSchedule
import org.quartz.CronExpression; //导入依赖的package包/类
private VmSchedule checkAndSaveSchedule(final VmScheduleVo schedule, final VmSchedule entity) {
// Check the subscription is visible
final Subscription subscription = subscriptionResource.checkVisibleSubscription(schedule.getSubscription());
if (schedule.getCron().split(" ").length == 6) {
// Add the missing "seconds" part
schedule.setCron(schedule.getCron() + " *");
}
// Check expressions first
if (!CronExpression.isValidExpression(schedule.getCron())) {
throw new ValidationJsonException("cron", "vm-cron");
}
// Every second is not accepted
if (schedule.getCron().startsWith("* ")) {
throw new ValidationJsonException("cron", "vm-cron-second");
}
entity.setSubscription(subscription);
entity.setOperation(schedule.getOperation());
entity.setCron(schedule.getCron());
// Persist the new schedules for each provided CRON
vmScheduleRepository.saveAndFlush(entity);
return entity;
}
示例5: add
import org.quartz.CronExpression; //导入依赖的package包/类
/**
* 注意:@RequestBody需要把所有请求参数作为json解析,因此,不能包含key=value这样的写法在请求url中,所有的请求参数都是一个json
*
*/
@RequiresPermissions("job:index")
@ResponseBody
@RequestMapping(value = "job", method = RequestMethod.POST)
public ResponseDTO add(@RequestBody JobAddAO jobAddAO) {
try {
//cron表达式合法性校验
CronExpression exp = new CronExpression(jobAddAO.getCron());
JobDetailDO jobDetailDO = new JobDetailDO();
BeanUtils.copyProperties(jobAddAO, jobDetailDO);
jobDetailService.addJobDetail(jobDetailDO);
} catch (ParseException e) {
e.printStackTrace();
return new ResponseDTO(0, "failed", null);
}
return new ResponseDTO(1, "success", null);
}
示例6: validateCronExpression
import org.quartz.CronExpression; //导入依赖的package包/类
@RequestMapping("withoutAuth/validateCron.html")
@ResponseBody
public Object validateCronExpression(String cronExpression){
try
{
boolean result = CronExpression.isValidExpression(cronExpression);
if(result)
{
return true;
}else
{
return false;
}
}catch(Exception e)
{
throw new AjaxException(e);
}
}
示例7: nextValidTimeFromCron
import org.quartz.CronExpression; //导入依赖的package包/类
public static Instant nextValidTimeFromCron(String patterns) {
String[] array = patterns.split("\\|");
Instant next = Instant.MAX;
for (String pattern : array) {
if (pattern.split(" ").length == 5) {
pattern = "0 " + pattern;
}
try {
List<String> parts = Arrays.asList(pattern.split(" "));
if (parts.get(3).equals("*")) {
parts.set(3, "?");
}
CronExpression cronExpression = new CronExpression(parts.stream().collect(Collectors.joining(" ")));
Instant nextPart = cronExpression.getNextValidTimeAfter(Date.from(Instant.now())).toInstant();
next = nextPart.isBefore(next) ? nextPart : next;
} catch (ParseException e) {
log.warn("Could not parse cron expression: {}", e.toString());
}
}
return next;
}
示例8: schedule
import org.quartz.CronExpression; //导入依赖的package包/类
@Override
public void schedule(String jobName, CronExpression cronExpression) {
try {
if(jobDetail != null){
jobDetail.setName(jobName);
jobDetail.setGroup(JOB_GROUP_NAME);
CronTrigger cronTrigger = new CronTrigger(jobName, TRIGGER_GROUP_NAME);
cronTrigger.setCronExpression(cronExpression);
scheduler.scheduleJob(jobDetail,cronTrigger);
if(!scheduler.isShutdown())
scheduler.start();
}else{
log.error("定时任务 "+jobName+" jobDetail对象为空");
//System.out.println("定时任务 "+jobName+" jobDetail对象为空");
}
// scheduler.rescheduleJob(name, Scheduler.DEFAULT_GROUP, cronTrigger);
} catch (SchedulerException e) {
log.error(e);
throw new RuntimeException(e);
}
}
示例9: registerCronJob
import org.quartz.CronExpression; //导入依赖的package包/类
/**
* Register cron job REST API
* @param message - JSON with cron expressions.
* @return JSON with status.OK
* @throws IOException, IllegalArgumentException
*/
@POST
@Path("cron/{notebookId}")
public Response registerCronJob(@PathParam("notebookId") String notebookId, String message) throws
IOException, IllegalArgumentException {
LOG.info("Register cron job note={} request cron msg={}", notebookId, message);
CronRequest request = gson.fromJson(message,
CronRequest.class);
Note note = notebook.getNote(notebookId);
if (note == null) {
return new JsonResponse<>(Status.NOT_FOUND, "note not found.").build();
}
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());
note.setConfig(config);
notebook.refreshCron(note.id());
return new JsonResponse<>(Status.OK).build();
}
示例10: cron
import org.quartz.CronExpression; //导入依赖的package包/类
/**
* 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);
}
示例11: validateCronExpression
import org.quartz.CronExpression; //导入依赖的package包/类
public static void validateCronExpression(String cronExpression) {
try {
if (cronExpression == null || cronExpression.equals("")) {
throw new IllegalArgumentException(String.format("Cron expression cannot be null or empty : %s", cronExpression));
}
StringTokenizer tokenizer = new StringTokenizer(cronExpression, " \t", false);
int tokens = tokenizer.countTokens();
String beginningToken = tokenizer.nextToken().trim();
if ("*".equals(beginningToken)) {
// For all practical purposes and for ALL clients of this library, this is true!
throw new IllegalArgumentException(
String.format("Cron expression cannot have '*' in the SECONDS (first) position : %s", cronExpression)
);
}
if (tokens > 7) {
throw new IllegalArgumentException(
String.format("Cron expression cannot have more than 7 fields : %s", cronExpression)
);
}
CronExpression.validateExpression(cronExpression);
} catch (ParseException e) {
throw new IllegalArgumentException(e.getMessage());
}
}
示例12: validate
import org.quartz.CronExpression; //导入依赖的package包/类
@Override
public void validate(Object object, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "task.groupName", "group.empty");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "task.name", "name.empty");
Task task = ((TaskDTO) object).getTask();
if (!StringUtils.isEmpty(task.getTimerSchedule())) {
// if there is a timer schedule, check it is valid for quartz cron trigger
try {
new CronExpression(task.getTimerSchedule());
} catch (ParseException e) {
errors.rejectValue("task.timerSchedule", "timer.schedule.invalid", e.getMessage());
}
}
if (task.getGroupName() != null && Constants.GROUP_NAME_ALL.equals(task.getGroupName().trim())) {
errors.rejectValue("task.groupName", "group.illegal", Constants.GROUP_NAME_ALL + " not allowed as group name");
}
}
示例13: registerCronJob
import org.quartz.CronExpression; //导入依赖的package包/类
/**
* Register cron job REST API
*
* @param message - JSON with cron expressions.
* @return JSON with status.OK
* @throws IOException, 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");
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());
note.setConfig(config);
notebook.refreshCron(note.getId());
return new JsonResponse<>(Status.OK).build();
}
示例14: registerCronJob
import org.quartz.CronExpression; //导入依赖的package包/类
/**
* Register cron job REST API
*
* @param message - JSON with cron expressions.
* @return JSON with status.OK
* @throws IOException, IllegalArgumentException
*/
@POST
@Path("cron/{noteId}")
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);
checkIfUserCanWrite(noteId, "Insufficient privileges you cannot set a cron job for this 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());
note.setConfig(config);
notebook.refreshCron(note.getId());
return new JsonResponse<>(Status.OK).build();
}
示例15: AnomalyDetectionFunctionCronDefinition
import org.quartz.CronExpression; //导入依赖的package包/类
public AnomalyDetectionFunctionCronDefinition(AnomalyDetectionFunction childFunc, String cronString)
throws IllegalFunctionException {
super(childFunc);
/*
* Use local timezone of the system.
*/
evalTimeZone = TimeZone.getDefault();
try {
cronExpression = new CronExpression(cronString);
cronExpression.setTimeZone(evalTimeZone);
} catch (ParseException e) {
throw new IllegalFunctionException("Invalid cron definition for rule");
}
}