I am using Quartz Scheduler in Java to run cron jobs. This is the first time I am using this framework to run the cron jobs so I am having some confusion.
I was following this tutorial to get the better understanding how to use Quartz framework.
I am trying to run JobA every week and every month so I started with basic example -
Here is my example which I have got so far.
public class JobA implements Job {
@Override
public void execute(JobExecutionContext context)
throws JobExecutionException {
System.out.println("Job A is runing");
// print whether it is week or month
}
}
Below is my CronTriggerExample which schedules the job to run
public class CronTriggerExample {
public static void main(String[] args) throws Exception {
JobKey jobKeyA = new JobKey("jobA", "group1");
JobDetail jobA = JobBuilder.newJob(JobA.class).withIdentity(jobKeyA)
.build();
Trigger trigger1 = TriggerBuilder
.newTrigger()
.withIdentity("dummyTriggerName1", "group1")
.withSchedule(CronScheduleBuilder.cronSchedule("5 8 * * 6 ?"))
.build();
Scheduler scheduler = new StdSchedulerFactory().getScheduler();
scheduler.start();
scheduler.scheduleJob(jobA, trigger1);
}
}
Problem Statement:-
I am not sure how to run JobA every week and every month using the above code. What will be my cron tab entry for a week and month in my case? I don't want to run any Job between 8 PM till 5 AM and any random day is fine.
If JobA is running every week, then it should print out one-week and report_week. But if JobA is running every month, then it should print out one-month and report_one_month so the next question is - Is there any way, we can pass parameters to JobA when we try to run it?
The meaning of the 7 fields of cron in quartz:
second minute hour day month week year
year field is optional. * means every, for example, * in week field means every week, so you should use * in both week field and month field. Note
when the week field is specified, don't forget to use ? in day field.
My example cron entry for you requirement is:
0 0 0 ? * *
which means running the job every week and every month on 00:00:00, please tune it for your need.
For more information, reference: CronTrigger.
I hope it helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With