JobDetail job1 = JobBuilder.newJob(FirstJob.class).withIdentity("job1", "group1").build(); Trigger trigger1 = TriggerBuilder.newTrigger().withIdentity("cronTrigger1", "group1") .withSchedule(CronScheduleBuilder.cronSchedule("*/10 * * * * ?")).build(); Scheduler scheduler1 = new StdSchedulerFactory().getScheduler(); scheduler1.start(); scheduler1.scheduleJob(job1, trigger1); JobDetail job2 = JobBuilder.newJob(SecondJob.class).withIdentity("job2", "group2").build(); Trigger trigger2 = TriggerBuilder.newTrigger().withIdentity("cronTrigger2", "group2") .withSchedule(CronScheduleBuilder.cronSchedule(new CronExpression("0/7 * * * * ?"))).build(); Scheduler scheduler2 = new StdSchedulerFactory().getScheduler(); scheduler2.start(); scheduler2.scheduleJob(job2, trigger2); Thread.sleep(100000); scheduler1.shutdown(); scheduler2.shutdown();
I am trying to execute a Cron Job every 5 minutes of an hour but its not executing on time. I think that the time expression is wrong.
How do you set the time expression for a 1, 5 minute job and a 2 for 1 hour job?
Advertisement
Answer
For job 1, 5 minute, you can use:
*/5 * * * * ?
Because the first field is for minutes. If you specify * in this field, it runs every minutes. If you specify */5 in the 1st field, it runs every 5 minutes as shown above.
For job 2, 1 hour, you can use:
0 */1 * * *
Because the second field is for hours. If you specify * in this field, it runs every hour. If you specify */5 in the 2nd field, it runs every 5 hours as shown above.
Not related with cron but your code seems to be missing to pass expression as to TheLostMind comment.
Correct sentence For job 1:
Trigger trigger1 = TriggerBuilder.newTrigger().withIdentity("cronTrigger1", "group1") .withSchedule(CronScheduleBuilder.cronSchedule(new CronExpression("*/10 * * * * ?"))).build();
Hope it helps.