Gruber
Gruber

Reputation: 4558

Spring 3.0 @Scheduled annotation not working as expected

I use the @Scheduled annotation to make the function myProcess() in a Spring MVC application (version 3.0.6.RELEASE running on Apache Tomcat/7.0.26) run once every hour (3,600,000 ms = 1 hour):

@Scheduled(fixedRate = 3600000)
public void myProcess() { ... }

The function is executed as expected, but not in the morning (see the sample log times below for the latest 2 days). This happens every day. I see no exceptions in the log files. Have you got any ideas as to what could be the reason for this strange behavior?


Feb 13 02:11:15
Feb 13 03:11:16 
Feb 13 06:17:34
Feb 13 06:45:55 
Feb 13 07:03:22
Feb 13 07:31:57
Feb 13 08:11:16 
Feb 13 09:11:18
Feb 13 10:11:18 
Feb 13 11:11:28 

Feb 14 01:11:37
Feb 14 02:11:29
Feb 14 03:11:29 
Feb 14 06:19:51
Feb 14 06:49:17
Feb 14 07:35:57
Feb 14 08:11:29
Feb 14 09:11:35

Upvotes: 2

Views: 8801

Answers (2)

sp00m
sp00m

Reputation: 48807

I had the same kind of problem, but using the cron attribute:

// every day at midnight
@Scheduled(cron = "0 0 0 * * ?")
public void myProcess() {
}

I can't really remember the behavior it had, but it wasn't the one I expected. I finally found that it was probably depending on a bug in Spring 3.0.x. The solution I tried (and which worked), was to declare the task in the applicationContext.xml file, in addition to the annotation:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">

    ...

    <!-- scheduling and async -->
    <task:annotation-driven />
    <task:scheduled-tasks>
      <task:scheduled ref="myProcessHandler" method="myProcess" fixed-delay="0" />
    </task:scheduled-tasks>
    <bean id="myProcessHandler" class="path.to.MyProcessHandler" />

    ...

</beans>

Even if the fixed-delay attribute is necessary to fix the bug (as far as I know), it isn't taken into account, while the cron attribute of the @Scheduled annotation is.

I hope this will help.

Upvotes: 2

abalogh
abalogh

Reputation: 8281

I cannot give you an answer to the specific question, I would try using the recent version of Spring (3.2) because between 3.0 and 3.1 as far as I know significant changes have been implemented in this area.

However, in my experience I found the cronTrigger much better in all cases (it can do of course everything the fixedRate can and so much more)

Just define your properties like this:

<util:properties id="props" location=classpath:/application.properties" />
<context:property-placeholder properties-ref="props"  />
<task:annotation-driven />

And then use it:

@Scheduled(cron = "${cron.expression}")
public void scheduledTask() throws .. { .. }

Where in the application.properties you have something like: cron.expression = 0 0/60 * * * ?

Upvotes: 2

Related Questions