Multiple Spring Calls Scheduled Task

So, I have a little problem with some of the scheduled tasks that I announced using the Spring Annotation @Scheduled. First of all, this is my app-config:

<beans <!--Namespaces-->>
    <!-- Search for annotated beans -->
    <context:component-scan  base-package="com.my.package.task"/>

    <task:annotation-driven executor="myExecutor" scheduler="myScheduler"/>

    <task:executor id="myExecutor" pool-size="5"/>

    <task:scheduler id="myScheduler" pool-size="10"/>

    <tx:annotation-driven/>
</beans>

I also have an AppConfig class:

@Configuration
@ImportResource("classpath:/config/app-config.xml")
public class AppConfig {
     //Bean declarations but NO references to the Scheduled tasks or their classes
}

And here are the scheduled tasks that I announced:

public abstract class ScheduledTask {
     private ApplicationContext appContext;

     abstract void doSomething();

     protected getAppContext() {
          if(appContext == null) {
               appContext = new AnnotationConfigApplicationContext(AppConfig.class);
          }

          return appContext;
     }
     //Other common methods
}

@Service
public class Task1 extends ScheduledTask {    
     @Scheduled(cron="0 0 9 * * MON-FRI")
     public void doSomething() {
        System.out.println("Task1 -- Thread ID: " + Thread.currentThread().getId() + " Thread Name: " + Thread.currentThread().getName());
         //Update the database with new values
     }
}

@Service
public class Task2 extends Scheduledtask {
     @Scheduled(cron="0 0 10 * * MON-FRI")
     public void doSomething() {
          System.out.println("Task2 -- Thread ID: " + Thread.currentThread().getId() + " Thread Name: " + Thread.currentThread().getName());
          //Get some data from database and send email with data from DB
     }
}

Now the problem is that when these tasks are completed, I get several emails sent (see Task2). I added to print statements to find out if methods are called multiple times, and Task2 is executed twice by two different threads. I hope Spring will only run the scheduled task. Here is the result I get:

Task1 -- Thread ID: 10 Thread Name: myScheduler-1
Task2 -- Thread ID: 23 Thread Name: myScheduler-2
Task2 -- Thread ID: 11 Thread Name: myScheduler-2 

cron 4 , (, , /).

- , ? Spring "" , , @Scheduled . AppConfig app-config.xml?

+3

Source: https://habr.com/ru/post/1771816/


All Articles