开发者

Writing a cron Expression in springs

开发者 https://www.devze.com 2023-02-17 00:39 出处:网络
I am using springs task scheduler(ConcurrentTaskScheduler) to schedule my tasks. I am using the API public ScheduledFuture schedule(Runnable task,Trigger trigger)

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 u开发者_开发知识库sing 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
    }


Please find the below link

http://www.mkyong.com/spring/spring-quartz-scheduler-example/

In Spring we have that integrated quartz scheduler.Only xml configuration need to schedule the job.There you can configure cron expression as you like.

I would suggest you use spring quartz scheduler integration

0

精彩评论

暂无评论...
验证码 换一张
取 消