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.


Solution 1:

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}")

Solution 2:

I had @EnableScheduling in my app config. I had @Scheduled(fixedDelay=5000) in my scheduled task class. Even then it didn't work.

I added @Service to my scheduled task class and everything worked fine.

Solution 3:

I was having the same situation. I need to run cron scheduler every 1st day of the month and also when the application starts.

This is how I achieved using ApplicationListener.

import org.springframework.context.ApplicationListener;
import org.springframework.boot.context.event.ApplicationReadyEvent;

@Component
public class ApplicationReadyListner implements ApplicationListener<ApplicationReadyEvent> {
    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        // callYourTask();
    }
}