faisalbhagat
faisalbhagat

Reputation: 2150

SpringMVC How to start a thread with start of application

In my springmvc application i want to start a thread for some iterative work which is going to be repeated after every 30 seconds for the life of application. where should I start this thread should I write a separate servlet for it? or should I start it in some controller?

Upvotes: 2

Views: 1178

Answers (2)

Ker p pag
Ker p pag

Reputation: 1588

use scheduler than thread

fixedRate makes Spring run the task on periodic intervals even if the last invocation may be still running.

fixedDelay specifically controls the next execution time when the last execution finishes.

cron is a feature originating from Unix cron utility and has various options based on your requirements.

@Scheduled(fixedDelay =30000)
public void demoServiceMethod () {... }

@Scheduled(fixedRate=30000)
public void demoServiceMethod () {... }

@Scheduled(cron="0 0 * * * *")
public void demoServiceMethod () {... }

Upvotes: 4

the_marcelo_r
the_marcelo_r

Reputation: 1856

How about starting it with a ServletContextListener? Then it will be started as soon as your web application starts.

void contextInitialized(ServletContextEvent sce) Receives notification that the web application initialization process is starting.

http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContextListener.html

Also, about the scheduled task, you might want to consider options like these so you don't have to reinvent the wheel:

Cheers!

Upvotes: 1

Related Questions