Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Spring @Scheduled tasks executing twice

I have a simple test method here that is set to run every 5 seconds and it does, but looking at the System.out you can see it appears to be doing something odd.

@Scheduled(cron="*/5 * * * * ?") public void testScheduledMethod() {      System.out.println(new Date()+" > Running testScheduledMethod..."); } 

Output:

Wed Jan 09 16:49:15 GMT 2013 > Running testScheduledMethod... Wed Jan 09 16:49:15 GMT 2013 > Running testScheduledMethod... Wed Jan 09 16:49:20 GMT 2013 > Running testScheduledMethod... Wed Jan 09 16:49:20 GMT 2013 > Running testScheduledMethod... Wed Jan 09 16:49:25 GMT 2013 > Running testScheduledMethod... Wed Jan 09 16:49:25 GMT 2013 > Running testScheduledMethod... Wed Jan 09 16:49:30 GMT 2013 > Running testScheduledMethod... Wed Jan 09 16:49:30 GMT 2013 > Running testScheduledMethod... 

Why is it running TWICE (appear) each time?

like image 940
KS1 Avatar asked Jan 09 '13 16:01

KS1


People also ask

How does @scheduled work in spring?

Java Cron Expression 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 @scheduled annotation in spring?

The Scheduled annotation defines when a particular method runs. This example uses fixedRate , which specifies the interval between method invocations, measured from the start time of each invocation.

Does @scheduled create a new thread?

@Scheduled causes the code to be run in a separate thread, not necessarily new as it might come from a thread pool.


1 Answers

If you look at the documentation, there is a note that explicitly calls out this phenomenon.

The note is under section 25.5.1 at this link, and reads:

Make sure that you are not initializing multiple instances of the same @Scheduled annotation class at runtime, unless you do want to schedule callbacks to each such instance. Related to this, make sure that you do not use @Configurable on bean classes which are annotated with @Scheduled and registered as regular Spring beans with the container: You would get double initialization otherwise, once through the container and once through the @Configurable aspect, with the consequence of each @Scheduled method being invoked twice.

I understand that this is merely suggestion at this point, but I do not think we have enough information to diagnose the issue further.

like image 57
nicholas.hauschild Avatar answered Sep 20 '22 03:09

nicholas.hauschild