I'm building Java Web Project on Servlet 3.0, Spring 3, and some other stuff.
I'm trying to use Spring's @Sheduled task.
It is working fine, but when i undeploy war from Tomcat scheduled task continues running.How to stop it on Spring Container destroy?
UPDATE I've found what was the root of my problem - i instantiated Spring context twice. First time in web.xml as
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/servlet-context.xml
</param-value>
</context-param>
and second one in code like:
context = new ClassPathXmlApplicationContext(new String[]
{"/WEB-INF/spring/servlet- context.xml", "/WEB-INF/spring/beans.xml"});
So two instances of SheduledProcessor was created and ony one of them was destroyed. So spring destroys one it's aware about and second continues running making me to think that nothing was destroyed. Removing ClassPathXmlApplicationContext solved my problem.
Controller.java
package a.b.c;
imports...
@Controller
@RequestMapping("/")
public class ReceiverController {
@RequestMapping(method = RequestMethod.GET)
public String welcome(ModelMap model) {
new ClassPathXmlApplicationContext("config.xml", ReceiverController.class);
return "index";
}
}
ScheduledProcessor.java
package a.b.c;
imports..
@Service
public class ScheduledProcessor {
private Logger logger = LoggerFactory.getLogger(ScheduledProcessor.class);
@Scheduled(fixedDelay = 30000)
public void process() {
logger.info("Processing task");
}
}
spring-config.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="a.b.c"/>
<task:annotation-driven/>
</beans>
Log file output :
03 Jul 2013 11:32:34,436 [ INFO ] (ScheduledProcessor.process:17)-> Processing task
11:33:04,439 [ INFO ] (ScheduledProcessor.process:17)-> Processing task
Jul 2013 11:33:06,913 [ INFO ] (XmlWebApplicationContext.doClose:1042)-> Closing WebApplicationContext for namespace 'Test-servlet': startup date [Wed Jul 03 11:32:21 EEST 2013]; root of context hierarchy 03 Jul 2013 11:33:06,914 [ INFO ]
(DefaultListableBeanFactory.destroySingletons:444)-> Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1a56058: defining beans [scheduledProcessor,receiverController,org.springframework.context.annotation.internalConfigurationAnnotationProcessor, etc..; root of factory hierarchy **
03 Jul 2013 11:33:34,440 INFO -> Processing task
03 Jul 2013 12:34:0,440 INFO -> Processing task