Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring @Scheduled is executing task twice when using annotations

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>
like image 460
newbie Avatar asked May 31 '10 10:05

newbie


People also ask

How does @scheduled work in Spring?

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.

Is @scheduled asynchronous?

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.

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.


2 Answers

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.

like image 153
Chinbold Gansukh Avatar answered Oct 08 '22 05:10

Chinbold Gansukh


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.

like image 45
jlars62 Avatar answered Oct 08 '22 06:10

jlars62