Multiple Invocations of Spring Scheduled Task
So I am having a bit of a problem with some scheduled tasks I have declared using Spring's @Scheduled
annotation. First off here 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 a 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 I have declared:
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 I am getting is that when these tasks are run, I get multiple emails sent (see Task2). I added in the print statements to see if the methods were being called multiple times and Task2 is executed twice by 2 different threads. I would hope that Spring would only invoke a scheduled task once. Here is the output 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
And if I run it at night and set the cron jobs to be like 4hrs apart I start to get even more emails sent (thought I havent had a chance to see if this is due to multiple threads / method calls).
Does anyone have any ideas what could be causing the multiple invocations of the second task? I looked at the Spring Documentation and under the 'Note' it mentions that you can get multiple invocation if you initialize multiple instances of the @Scheduled
class at runtime. Could that be happening here with my AppConfig and app-config.xml?
精彩评论