Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Scheduled task does not start on application startup

I have a @Scheduled task in my application which is setup using CRON and run every 4 hours. The problem I face is that the CRON job does not start immediately after application startup but it starts only 4 hours after the application startup.

I tried to use a @PostConstruct method inside the task to invoke it, but that results in an error due to an uninitialized Spring context.

Please tell me how I can make the Scheduled task run immediately on application deployment and then on every 4 hours after the deployment.

EDIT:
I would not use a @PostConstruct since my scheduled method depends on other Beans , which are not initialized when this PostConstruct method runs for some reason.

like image 427
v1shnu Avatar asked Feb 15 '17 10:02

v1shnu


People also ask

How do I trigger a scheduler in spring boot?

The @EnableScheduling annotation is used to enable the scheduler for your application. This annotation should be added into the main Spring Boot application class file. The @Scheduled annotation is used to trigger the scheduler for a specific time period.

What is fixed delay in spring scheduler?

Schedule a Task at Fixed Delay In this case, the duration between the end of the last execution and the start of the next execution is fixed. The task always waits until the previous one is finished. This option should be used when it's mandatory that the previous execution is completed before running again.

What is ThreadPoolTaskScheduler?

ThreadPoolTaskScheduler ThreadPoolTaskScheduler is well suited for internal thread management, as it delegates tasks to the ScheduledExecutorService and implements the TaskExecutor interface – so that single instance of it is able to handle asynchronous potential executions as well as the @Scheduled annotation.


1 Answers

By 0 */4 * * * you specify "At minute 0 past every 4th hour (0:00, 4:00, 8:00 etc.)", which is not at startup time and then every 4 hours as I think you want. You can specify initial delay and rate by:

@Scheduled(initialDelay=0, fixedRate=4*60*60*1000)

If you are worried about hard-coded values, you can still provide config value:

@Scheduled(initialDelay=0, fixedRateString = "${some.config.string}")
like image 114
Tomas F. Avatar answered Oct 22 '22 06:10

Tomas F.