本文整理匯總了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");
}
}