How to specify a Cron job for the following described Scenario? - java

Using Java & Quartz, is there a way to specify a Cron job (using a cron expression OR not) for the following scenario;
(Parent-Event) ==> Start at <Time-X of day> & execute once every 5 days{
(Child-Event) ==> Start at <Time-X of day> & execute 3-times at 1 hour intervals{...}
}

TriggerBuilder class has startAt and endAt method. startAt mekes start executing a job at specified date, whereas endAt makes stop executing a job at specified date.
Child-Event is scheduled by Parent-Event, and Time-X should be less than 22.
For Parent-Event:
Cron expression: "0 0 X * * ?"
startAt: When you want to start a job
endAt : startAt date + 5 days
For Child-Event:
Cron expression: "0 0 X-X+2 * * ?"
endAt : The midnight of the day when executing Parent-Event

Related

Issue with cron expression in java spring boot application

I am running a job scheduler in spring boot application.
To execute job every 5 min, I am using below cron expression
#Scheduled(cron = "0 0/5 * * * *", zone ="EST").
This is working fine
But when I try to execute the same job at a specific time, for instance at 11:30 AM, I am using below cron expression
#Scheduled(cron = "0 30 11 * * *", zone ="EST")
This is not working
I couldn't find any mistake w.r.t syntax. Please help if I am doing anything wrong

Spring SimpleTriggerContext get proper nextExecutionTime

I have job that will run every 10 mins. I don't want to use Spring Scheduler based on last job run next job will schedule to run. Suppose First job ran at 10:15 AM, Subsequent job needs to run at 10:25 AM. When i googled i saw posts with nextExecutionTime. When i use nextExecutionTime my subsequent job is running at 10:20 instead of 10:25. Below is my code, Can any one give an idea how i can run my job at exact 10 mins from last run.
CronTrigger trigger = new CronTrigger("0 0/10 * * * ?");
SimpleTriggerContext triggerContext = new SimpleTriggerContext();
triggerContext.update(Date.from(ZonedDateTime.now().toInstant()), Date.from(ZonedDateTime.now().toInstant()), Date.from(ZonedDateTime.now().toInstant()));
Date nextFireAt = trigger.nextExecutionTime(triggerContext);
System.out.println(nextFireAt);
Can you try the below. I provide below the sequence.
Get the date now.
Add 10 mins to the date and get a new updated date
Update the like triggerContext.update(null, null, date in which you have added 10 mins);

Start a scheduled spring batch job 5 seonds after start of previous one

I have a spring batch job with a #Scheduled(fixedDelay=5000) annotation. But it starts 5 seconds after the end of the previous execution. How can I start it 5 seconds after the start of the previous execution?
Use #Scheduled(fixedRate = 5000). You can also use a CRON expression #Scheduled(cron = "*/5 * * * * ?") but it seems like an overkill.

Spring execute method every 15 minutes

I tried to use cron expression from this site http://www.cronmaker.com/
#Scheduled(cron = "0 0/15 * 1/1 * ? *")
public void clearRps() {
}
But it throws: java.lang.IllegalStateException: Encountered invalid #Scheduled method 'clearRps': Cron expression must consist of 6 fields (found 7 in "0 0/15 * 1/1 * ? *")
Just use the following cron:
#Scheduled(cron = "0 0/15 * * * *")
Spring cron expression syntax slightly differs from unix cron expression. One immediate difference - it supports 1 less field (6 rather than 7).

How to use #Scheduled(cron) with SpEL in spring?

I have a method that I want spring to schedule - for that matter I'm using the #Scheduled annotation - and to be more exact, I'm using a cron expression.
My cron expression is in a property file that is called scheduler.properties.
When I'm using it as a placeholder #Scheduled(cron="${cron}") - everything works great; but I want to use SpEL ( #Scheduled(cron="#{scheduler['cron']}") ) , and it does't work - throws the following exception:java.lang.IllegalArgumentException: cron expression must consist of 6 fields (found 1 in #{scheduler['cron']})
What am I doing wrong here?
EDIT:
Here is my cron expression from the properties file: cron=0 0/1 * * * ?
Here is the stack trace that I get:
java.lang.IllegalArgumentException: cron expression must consist of 6 fields (found 1 in #{scheduler['cron']})
at org.springframework.scheduling.support.CronSequenceGenerator.parse(CronSequenceGenerator.java:233)
at org.springframework.scheduling.support.CronSequenceGenerator.<init>(CronSequenceGenerator.java:81)
at org.springframework.scheduling.support.CronTrigger.<init>(CronTrigger.java:54)
at org.springframework.scheduling.support.CronTrigger.<init>(CronTrigger.java:44)
at org.springframework.scheduling.config.ScheduledTaskRegistrar.afterPropertiesSet(ScheduledTaskRegistrar.java:188)
at org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor.onApplicationEvent(ScheduledAnnotationBeanPostProcessor.java:209)
at org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor.onApplicationEvent(ScheduledAnnotationBeanPostProcessor.java:1)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:97)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:324)
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:929)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:467)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:384)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:283)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4723)
at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5226)
at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5221)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
SECOND EDIT:
It seems that spring is trying to parse the following string as the cron experssion "#{scheduler['cron']}" insraed of the actual cron expression itself.
According to the error message, the value of the cron expression in your properties file is incorrect.
It does not conform to the expected syntax.
The value should contain six fields and look something like this.
* 10 * * * *
Here's the code that throws this exception
/**
* Parse the given pattern expression.
*/
private void parse(String expression) throws IllegalArgumentException {
String[] fields = StringUtils.tokenizeToStringArray(expression, " ");
if (fields.length != 6) {
throw new IllegalArgumentException(String.format(""
+ "cron expression must consist of 6 fields (found %d in %s)", fields.length, expression));
}
It may not be possible to externalize cron configuration using spEL in an Annotation.
The alternatives are to use XML or use the cron expression.
http://forum.springsource.org/showthread.php?91203-Scheduled-and-externalization-of-configuration-for-fixedDelay-and-fixedRate-problem
Always specify like this in property file: Notice the space in between frequency.
run refresh job every day a 9am
job.cron.rate=0 0 9 * * *
Example patterns:
* "0 0 * * * *" = the top of every hour of every day.
* "*/10 * * * * *" = every ten seconds.
* "0 0 8-10 * * *" = 8, 9 and 10 o'clock of every day.
* "0 0/30 8-10 * * *" = 8:00, 8:30, 9:00, 9:30 and 10 o'clock every day.
* "0 0 9-17 * * MON-FRI" = on the hour nine-to-five weekdays
* "0 0 0 25 12 ?" = every Christmas Day at midnight
Use it like this in Code:
#Scheduled(cron = "${job.cron.rate}")
public void perform() throws InterruptedException {
}
I had a similar issue and resolved it by reading property file with context:property-placeholder
<util:properties id="applicationProps" location="/WEB-INF/classes/properties/application.properties" />
**<context:property-placeholder properties-ref="applicationProps" />**
Hope it helps someone!!
It works. I spent days figuring out... but this indeed works.
You should set environment variable like you do for JAVA_HOME etc.
Close your IDE.
export cron_scheduler_expression="0 19 21 * * *"
Then restart your IDE, Eclipse or NetBeans whatever you are using.
#Scheduled(cron = "${cron_scheduler_expression}")
public void runSchedulerTask(){
}

Categories

Resources