I want to create Cron expression for 5 days and run every day from starting date.
start date :- 30-04-2017
and
End date:- 03-05-2017
Run every day at 1:00PM
try following lines of code,
SimpleTriggerFactoryBean simpleTriggerFactoryBean=new SimpleTriggerFactoryBean(); simpleTriggerFactoryBean.setJobDetail(job.getObject()); simpleTriggerFactoryBean.setStartTime(startDateTimeInMillis); simpleTriggerFactoryBean.setRepeatInterval(24*60*60*1000); simpleTriggerFactoryBean.setRepeatCount(5); simpleTriggerFactoryBean.setName("name"); simpleTriggerFactoryBean.afterPropertiesSet();
I hope,this will resolve your problem.
Related
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();
I am using cron-utils jar for generating cron expression
0 0 8 ? 1/1 5#3 *
3rd Thursday of every month at 8 o' clock
Below is my code for above expression:
CronBuilder withMonth = CronBuilder.cron(
CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ)
).withYear(always()).withDoM(QuestionMark.questionMark())
.withMonth(on(3, SpecialChar.HASH));
withMonth.withDoW(on(5)).withHour(on(8)).withMinute(on(0)).withSecond(on(0));
Cron instance = withMonth.instance();
System.out.println(instance.asString());
But I'm getting the following exception:
value missing for a#b cron expression
finally found solution
.withDoW(on(NUM_DAY_WEEK,SpecialChar.HASH, NUM_DAY_MONTH);
it will generate like 5#3
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
}
I am trying to build a Trigger in Quartz Scheduler API which should get executed with following criteria.
Start on particular date (Jan 25, 2012)
Start at predefined time (08.00.00 AM)
Every Week.
Can be scheduled for alternate week or every 3 week (if not every week)
On these particular days of week (Monday,Tuesday,Friday etc)
I have created the following expression
newTrigger().withIdentity(cronTriggerDTO.getTiggerId(), "simpleGroup")
.startAt(getTriggerExecutionDate(cronTriggerDTO))
.withSchedule(calendarIntervalSchedule().withIntervalInWeeks
(cronTriggerDTO.getWeeklyInterval())).build();
but I am confused how I should add the condition to execute this trigger on particular days of week
I'd use CronScheduleBuilder.cronSchedule(String cronExpression), like this:
newTrigger().withIdentity(cronTriggerDTO.getTiggerId(), "simpleGroup")
.startAt(getTriggerExecutionDate(cronTriggerDTO))
.withSchedule(CronScheduleBuilder.cronSchedule("0 0 * * 1,2,5"))
.build();
Use DailyTimeIntervalScheduleBuilder
Set daysOfWeek = new HashSet();
daysOfWeek.add(1);
daysOfWeek.add(2);
daysOfWeek.add(5);
newTrigger().withIdentity(cronTriggerDTO.getTiggerId(), "simpleGroup")
.startAt(getTriggerExecutionDate(cronTriggerDTO))
.withSchedule(dailyTimeIntervalSchedule()
.onDaysOfTheWeek(daysOfWeek)
.startingDailyAt(new TimeOfDay(8,0)))
.build();
Use cron trigger and below is the simple way to prepare cron expression
int second = 53;//prepare from the time selected from UI(fire time)
int minute=0;
int hour=8;
String dayOfWeek="1,3";//prepare it from the days you get from UI(give check box values as 1 for SUN,....)
String cronExpression = String.format("%d %d %d ? * %s",second,minute , hour, dayOfWeek);
newTrigger()
.withIdentity(cronTriggerDTO.getTiggerId(), "simpleGroup")//
.withSchedule(cronSchedule(cronExpression)//
.startAt(getTriggerExecutionDate(cronTriggerDTO))
.build();
Then schedule the job..,hope this helps you.
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.