1
votes

I am new for scheduler in spring. I read so many articles on @scheduled , ScheduledExecutorService & TimerTask .

So as per my knowledge @scheduled and ScheduledExecutorService are most of same functionality but if your code is in spring so its better to user @Scheduled annotation in your code.

So my question is Suppose I want to run some task after 15 minutes my program start that means initial delay is 15 min and that task should be run every after 5 minutes means fixedRate is 5 minuter. So by using cron expression how can I achieve it?

Read following links :

  1. https://dzone.com/articles/schedulers-in-java-and-spring
  2. https://crontab.guru/#15____
  3. https://www.baeldung.com/spring-scheduled-tasks

I can achieve the same using following code but I want to write this code with cron expression.

Code :

@Configuration
@EnableScheduling
public class ScheduledConfiguration {
    @Scheduled(fixedDelay = 5000, initialDelay = 1000)
    public void scheduleFixedRateWithInitialDelayTask() {

        long now = System.currentTimeMillis() / 1000;
        System.out.println("Fixed rate task with one second initial delay - " + now);
    }
}
2
Cron works on date/time, so you can't schedule it relative to application start time. - Cray

2 Answers

1
votes

Cron is a syntax which aligns tasks to a calendar. e.g. every Sunday at 3PM.

It cannot define events like "15 minutes after my application starts", because the application start time is unknown, and could be anything. It needs to align to the clock. E.g. 15 minutes past the hour.

Similarly, it does not have support for a task where the initial delay is different from the interval.

If you want to use cron, it can be easily be scheduled every 15 minutes, but you will have to accept that the first invocation could take anywhere from ~1 second to ~14 mins 59 secs, depending when your app starts.

1
votes

You can't mix intial-delay and cron.. cron are used when delay and rates are not sufficient and you need more flexibility.

But you can schedule with a cron every 15 minutes like this :

@Scheduled(cron = "* /15 * * * *)