How to create background process in spring webapp? How to create background process in spring webapp? multithreading multithreading

How to create background process in spring webapp?


Spring has a comprehensive task execution framework. See the relevant part of the docs.

I suggest having a Spring bean in your context, which, when initialized, submits your background Runnable to a SimpleAsyncTaskExecutor bean. That's the simplest approach, which you can make more complex and capable as you see fit.


I would go ahead and look at the task scheduling documentation linked by skaffman, but there's also a simpler way if all you really want to do is fire up a background thread at context initialization time.

<bean id="myRunnableThingy">  ...</bean><bean id="thingyThread" class="java.lang.Thread" init-method="start">  <constructor-arg ref="myRunnableThingy"/></bean>


As another option, one can now use Spring's scheduling capabilities. With Spring 3 or higher, it has a cron like annotation that allows you to schedule tasks to run with a simple annotation of a method. It's also friendly with autowiring.

This example schedules a task for every 2 minutes with an initial wait (on startup) of 30 seconds. The next task will run 2 minutes after the method completes! If you want it to run every 2 minutes exactly, use fixedInterval instead.

@Servicepublic class Cron {private static Logger log = LoggerFactory.getLogger(Cron.class);@Autowiredprivate PageService pageService;@Scheduled(initialDelay = 30000, fixedDelay=120000)  // 2 minutespublic void cacheRefresh() {    log.info("Running cache invalidation task");    try {        pageService.evict();    } catch (Exception e) {        log.error("cacheRefresh failed: " + e.getMessage());    }}}

Be sure to also add @EnableAsync@EnableScheduling to your Application class to enable this feature.