I have made task using Spring @Scheduled annotation, but for some reason it is executing task twice. My Spring Framework version is 3.0.2.
@Service
public class ReportService {
@Scheduled(fixedDelay=1000 * 60 * 60* 24)
@Transactional
public void dailyReportTask()
{
... code here ...
}
}
Here is my XML:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<task:scheduler id="taskScheduler" />
<task:executor id="taskExecutor" pool-size="1" />
<task:annotation-driven executor="taskExecutor"
scheduler="taskScheduler" />
</beans>
We can turn any method in a Spring bean for scheduling by adding the @Scheduled annotation to it. The @Scheduled is a method-level annotation applied at runtime to mark the method to be scheduled. It takes one attribute from cron , fixedDelay , or fixedRate for specifying the schedule of execution in different formats.
Note that scheduled tasks don't run in parallel by default. So even if we used fixedRate, the next task won't be invoked until the previous one is done. Now this asynchronous task will be invoked each second, even if the previous task isn't done.
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.
it is happening because of context listener
Just remove
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
from web.xml
it should work.
I had this same problem, and I eventually found out that the problem was occurring as a result of the beans being created in the root context
as well as the servlet context
.
So, to fix this, you need to separate the creation of the beans into the appropriate contexts.
This answer explains really well how to that and was what fixed my problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With