I need to execute method periodically when I start server, I'm using Tomcat v6.0 Server, and as a frameworks, I use hibernate, JSF, Primefaces and spring. Should I add something in web.xml ?
Asked
Active
Viewed 227 times
2 Answers
0
There are several solutions, you can achive your need by one of this way.
Assume your method is a Dispatch task you scheduled to run once in some interval sec
Keep your task in separate class and schedule it after your context sucessfully initilized
ScheduledExecutorService scheduledExcecutor = Executors.newScheduledThreadPool(3);
scheduledExcecutor.scheduleWithFixedDelay(yourTaskInstance, 0,
sleepInterval, TimeUnit.MILLISECONDS);
You can schedulewith Fixed Rate also,check ScheduledExecutorService document
Shutdown it gracefully when your server is down.

vels4j
- 11,208
- 5
- 38
- 63
0
Based on your application environment, you can add startup hook with any of the below ways.
Spring
You can implement Lifecycle or SmartLifeCycle interface for application context's startup and shutdown phases.
Tomcat
You can add listener by implementing LifecycleListener
Generic
- ServletContextListener
- Configuring servlet to load-on-startup.
Afterwards, you can add ScheduledThreadPoolExecutor to execute tasks periodically.

Nayan Wadekar
- 11,444
- 4
- 50
- 73