This question already has an answer here:
I am using JSP/Servlet on Apache Tomcat. I have to run a method every 10 minutes. How can I achieve this?
This question already has an answer here:
I am using JSP/Servlet on Apache Tomcat. I have to run a method every 10 minutes. How can I achieve this?
As you're on Tomcat, which is just a barebones servletcontainer, you can't use EJB's
@Schedule
for this which is recommended by Java EE specification. Your best bet is then theScheduledExecutorService
from Java 1.5'sjava.util.concurrent
package. You can trigger this with help of aServletContextListener
like follows:where the
SomeTask
class look like this:If you were actually using a real Java EE container with EJB support and all on em (like Glassfish, JBoss AS, TomEE, etc), then you could use a
@Singleton
EJB with a@Schedule
method. This way the container will worry itself about pooling and destroying threads. All you need is then the following EJB:Note that this way you can continue transparently using container managed transactions the usual way (
@PersistenceContext
and so on), which isn't possible withScheduledExecutorService
— you'd have to manually obtain the entity manager and manually start/commit/end transaction, but you would by default already not have another option on a barebones servletcontainer like Tomcat anyway.Note that you should never use a
Timer
in a supposedly "lifetime long" running Java EE web application. It has the following major problems which makes it unsuitable for use in Java EE (quoted from Java Concurrency in Practice):Timer
is sensitive to changes in the system clock,ScheduledExecutorService
isn't.Timer
has only one execution thread, so long-running task can delay other tasks.ScheduledExecutorService
can be configured with any number of threads.TimerTask
kill that one thread, thus makingTimer
dead, i.e. scheduled tasks will not run anymore (until you restart the server).ScheduledThreadExecutor
not only catches runtime exceptions, but it lets you handle them if you want. Task which threw exception will be canceled, but other tasks will continue to run.Read on ScheduledExecutorService it has to be initiated by a ServletContextListener
Also, you may try using the Java Timer from a ServletContextListener but it's not recommended in a Java EE container since it takes away control of the Thread resources from the container. (the first option with ScheduledExecutorService is the way to go).
And
MyTask
that implementsTimerTask
is a class that implements theRunnable
interface so you have to override the run method with your code: