2
votes

I have code running every two minutes using the @Scheduled annotation. However, our jobs tend to run for longer periods of time. As I understand it, the @Scheduled annotation queues up the new jobs and runs them as soon as the first job is complete. I do not want this to happen. I want there to be only 1 instance of the job running and no queued instances. How can I do this?

@Scheduled(cron = "0 */2 * * * ?")
public void twoMinMethod() {
    // code here
}
1
Well it depends. If you have a TaskExecutor with multiple threads and there are free threads you have multiple concurrent executions. Until the pool runs out then, based on the selected strategy, the jobs are queued, discarded or you will receive an exception. So actually it depends. If you want a single instance you need to use a scheduler like quartz which provides support for this. - M. Deinum

1 Answers

2
votes

If you don't need to run the jobs exactly on the minute, you might want to switch to the other non-crontab syntax which will allow this sort of thing. The example below will execute the method, wait two minutes from when it finishes, and then execute it again.

@Scheduled(fixedDelay=120000)
public void twoMinMethod() { ... }

See more at the Spring Documentation.