I am using springs task scheduler(ConcurrentTaskScheduler) to schedule my tasks. I am using the API
public ScheduledFuture schedule(Runnable task,Trigger trigger)
to execute my tasks.The trigger I am using is the CronTrigger.
I am initializing the trigger using the following statement
Trigger trigger = new CronTrigger(cronExp);
I need to write a cronExp in such a way that it starts at a specific date and executes daily from then on.
I checked out the API for ConcurrentTaskScheduler but I could find appropriate API to achieve/I might have missed some API.
Can anyone suggest me a way to achieve the above requirement?
To my knowledge, you can't use Spring's CronTrigger
to start only from a certain date.
Cron syntax doesn't support running something daily from an arbitrary date; it supports EITHER running something daily OR running once on an arbitrary date — but not both at once. That means you could use two triggers: have one cron trigger set to trigger on your start date; then create a new daily trigger when that first trigger occurs.
However this only works properly with if the cron trigger you are using supports years, for example Quartz has an option year field in its cron trigger. Spring's CronTrigger
doesn't support years. So if you did try to schedule something for a specific date (say 0 0 12 26 1 ?
for noon on Australia day) then it would run every year, not just once, causing duplicate triggers to be created each year.
Instead I recommend creating a simple trigger to run daily, ie:
Trigger trigger = new CronTrigger("0 0 12 * * ?);
So your code will run daily. Then add a simple date check in your code: if you haven't reached the start date then skip your task, ie:
if ((new Date()).after(startDate)) {
// Run your task here
}