Java Scheduler Quartz Cron Trigger Time Setting - java

I am using Quartz for Scheduling my job in java. I have used "CronTrigger" for setting my time.
I want to fire my Job each day at 11:55 Pm in night. What should i write in the setCronExpression(" ") for having my Job Done. .??
What i thought of the Code is:---
CronTrigger trigger = new CronTrigger();
trigger.setName("runMeJob");
trigger.setCronExpression("0 55 23 * * ?");
Is the above code correct or should i do some modifications in it????

It would be: 0 55 23 1/1 * ? *
There is a nice website exactly for your case: CronMaker
CronMaker is a utility which helps you to build cron expressions.
CronMaker uses Quartz open source scheduler. Generated expressions are
based on Quartz cron format.

Related

Quartz CronScheduleBuilder.atHourAndMinuteOnGivenDaysOfWeek don't working

I needing to use Quartz to execute a job. and when I try create a trigger on this mode :
Trigger trigger = TriggerBuilder.newTrigger().withIdentity(identityTRIGGER, "grupo 01") .withSchedule(CronScheduleBuilder.atHourAndMinuteOnGivenDaysOfWeek(11, 20, DateBuilder.THURSDAY)).build();
don´t fired at 11:20 on thursday.
I´ve tried to do (with cron expression):
Trigger trigger = TriggerBuilder.newTrigger().withIdentity(identityTRIGGER, "grupo 01").withSchedule(CronScheduleBuilder.cronSchedule("0 20 11 * * 5 *") ).build();
and don't work eigther- shows the following message:
Caused by: java.text.ParseException: Support for specifying both a day-of-week AND a day-of-month parameter is not implemented
**OBS: If I use another chron expression (like "0/10 * * * * ?") this work **
what´s wrong with my trigger ?
tnx advanced
To prevent exception "ParseException: Support for specifying both a day-of-week AND a day-of-month parameter is not implemented" do not use the * (all) value for day-of-month, but you could use ? (any) instead.
This is the strange implementation limitation of quartz.
So, you could use expression
0 20 11 ? * 5 *

How to stop quartz cron scheduler after specified number of occurrences?

I have a requirement where user can set a end date or can set a specific number of occurrences before stopping any job.
As for example,
Consider I have to send sms to a specific number and that should start from now and the sms will be sent in each 5 minutes.
Now based on user's choice the above job will be stopped on a specific time or after n number of occurrences.
And I am using cron scheduler of quartz.
Now stopping it at a specific date time is easy and I have done it like following way;
trigger = TriggerBuilder.newTrigger()
.startAt(startDateObj)
.endAt(endDate)
.withIdentity(uniqueID, "group1")
.withSchedule(
CronScheduleBuilder.cronSchedule(cronString)
)
.build();
But what to do if I have to stop it after n number of occurrences? I know it can be done with simple schedule like;
simpleSchedule().withRepeatCount(1).withIntervalInSeconds(15)
But how to do the same for cron scheduler? For some reasons I can not shift to any other type of schedule except cron.
Any help will be great for me.
Please let me know if any more data is required.
Thanks in advance.
You can count the endDate using computeEndTimeToAllowParticularNumberOfFirings() method. (That name though!).
See the following example:
CronTrigger trigger = new Trigger()
.withIentity("some_id")
.withSchedule(buildCronScheduler("some_cron_exp"))
.build();
Date endDate = TriggerUtils.computeEndTimeToAllowParticularNumberOfFirings(
(OperableTrigger) trigger,
new BaseCalendar(Calendar.getInstance().getTimeZone()),
repeatCount);
trigger = trigger.getTriggerBuilder().endAt(endDate).build();

How to configure cronSchedule() / cron expression in Quartz library to run same job every day at 11am, 12am, 15am, 17am etc?

I am using Quartz library to add cron timer to my application.
Sample usage is explained here, specifying run periodicity in this API is done thru so-called "cron string" (cron expression) - it is well-explained in examples here and in official docs here.
CronTrigger trigger = newTrigger()
.withIdentity("trigger1", "group1")
.withSchedule(cronSchedule("0/20 * * * * ?")) // cron string
.build();
I understand how to run a task specifying starting point + periodicity (say, at 11am every day, every Friday, etc).
But I need to run it every day at 11am, 12am, 3pm, 7pm etc - I can just enumerate exact times. How can I specify that? I need same task (job) be executed every day exactly at these many times.
It is stupid to create so many Trigger(s), each with separate cron expression. Is there a nice solution?
Here, docs say:
, - used to specify additional values. For example, “MON,WED,FRI” in
the day-of-week field means “the days Monday, Wednesday, and Friday”.
So maybe this works: "0 0 11am,12am,3pm,7pm * * ?" ?
P.S. Or all I can do is to create a separate Trigger for every hour and then add all such Triggers (with same job) to Scheduler like
myScheduler.scheduleJob(sameJob, trigger11am);
myScheduler.scheduleJob(sameJob, trigger12am);
myScheduler.scheduleJob(sameJob, trigger3pm);
myScheduler.scheduleJob(sameJob, trigger7pm);
Yes, this is the way it can be done:
// setup CronTrigger
// misfire policies (when app was down at scheduled time):
// https://www.nurkiewicz.com/2012/04/quartz-scheduler-misfire-instructions.html
Trigger trigger = TriggerBuilder
.newTrigger()
.withIdentity("triggerName", "myGroupName")
.withSchedule(
// at 11:30am, 12:30am, 03:30pm, 06:30pm, etc every day, including Sunday, Monday, days-off
CronScheduleBuilder.cronSchedule("0 30 11,12,15,18,21,23 * * ?")
// don't run missed jobs (missed when app was down)
.withMisfireHandlingInstructionDoNothing())
.build();
Here official examples at the bottom confirm it - see "Fire at 2:10pm and at 2:44pm every Wednesday".

Java Spring do scheduled task at a specific time of specific timezone

I'm developing a website with Spring and Hibernate (the website is about stock trading).
At about 12 AM everyday, I need to cancel all orders. Currently my solution is using a scheduled task that runs every hour:
<task:scheduled ref="ordersController" method="timeoutCancelAllOrders" fixed-delay="60*60*1000" />
Then in the method timeoutCancelAllOrders, I get the current time and check, if it's between 11PM and 12AM then do the task
The way I see it, task schedule starts when I start the Server ( I'm using Tomcat in Eclipse), but when I deploy it on an online hosting ( I'm using Openshift), I have no idea when is the starting time of task schedule.
My question is:
1: How to do it more automatic ? Is there anything like myTask.startAt(12AM) ?
2: I'm living in Vietnam but the server (Openshift) is located in US, so here's how I do the check :
Date currentTime = new Date();
DateFormat vnTime = new SimpleDateFormat("hh:mm:ss MM/dd/yyyy ");
vnTime.setTimeZone(TimeZone.getTimeZone("Asia/Ho_Chi_Minh"));
String vietnamCurrentTime = vnTime.format(currentTime);
String currentHourInVietnam = vietnamCurrentTime.substring(0, 2);
System.out.println(currentHourInVietnam);
if(currentHourInVietnam.equals("00")){
// DO MY TASK HERE
}
That looks stupid. How can I improve my code ?
Use a CRON specification:
<task:scheduled ref="beanC" method="methodC" cron="0 0 0 * * ?"/>
Run at midnight every day.
If you instead annotate your method, you can specify the time zone:
#Scheduled(cron="0 0 0 * * ?", zone="Asia/Ho_Chi_Minh")
public void methodC() {
// code
}

Quartz Scheduing: Using DailyCalendar

I am trying to schedule a quartz job according to the following plan:
Job runs daily and should only be executed between 9:30am and 6:00pm. I am trying to achieve this via DailyCalendar. Here what my DailyCalendar looks like:
DailyCalendar dCal = new DailyCalendar(startTimeString, endTimeString);
dCal.setTimeZone(TimeZone.getDefault());
dCal.setInvertTimeRange(true);
where start and end time strings are of the format HH:MM
Next, I try to schedule this job:
Scheduler myscheduler = StdSchedulerFactory.getDefaultScheduler();
SimpleTrigger trigger = new SimpleTrigger();
myscheduler.addCalendar("todcal", cal, true, true);
trigger.setName("TRIGGER " + alertName);
trigger.setJobName(alertName);
trigger.setJobGroup(alertName);
trigger.setCalendarName("todcal");
logger.info("Adding TOD job");
myscheduler.scheduleJob(trigger); // line causing exception
myscheduler.start();
As soon as scheduleJob is called I see the following Exception:
Based on configured schedule, the given trigger will never fire.
The configuration seems fine to me but I cant find any sample code for using DailyCalendar so I could be wrong here. Please help
You don't seem to be setting a repeat count or repeat interval on your trigger. So it will only fire once at the current moment (because you did not set a future start time), which probably happens to be during the calendar's exclusion time - which is why it would be calculated that it will never fire.
Job runs daily and should only be
executed between 9:30am and 6:00pm.
How often should the job be executed within that timeframe? Once? Once an hour? Every 10 seconds?
You need to define the repeat interval for your trigger. Look at setRepeatInterval(long repeatInterval) method of SimpleTrigger. It defines in milliseconds the interval with which the trigger will repeat.

Categories