18

I want to run background process in parallel with my spring-mvc web-application. I need a way to start in automatically on context loading. Background process is a class that implements Runnable. Is spring-mvc has some facilities for that?

skaffman
  • 398,947
  • 96
  • 818
  • 769
Vladimir
  • 12,753
  • 19
  • 62
  • 77

3 Answers3

19

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.

Jurn Ho
  • 69
  • 1
  • 5
skaffman
  • 398,947
  • 96
  • 818
  • 769
  • updated doc link: https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/integration.html#scheduling – nograde Mar 14 '18 at 16:01
7

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>
washley
  • 71
  • 2
  • 1
    Does that work well with context shutdown and so on? – Bartosz Radaczyński Jul 09 '14 at 14:18
  • 1
    That's a good question, shutdown might be tricky. Ideally you'd want to do an `interrupt()` followed by a `join()`. Unfortunately, I don't believe you can have two `destroy-method`s, so the best you could do is `destroy-method="interrupt"`. For proper shutdown behavior I would recommend implementing [Lifecycle](http://docs.spring.io/spring/docs/4.1.0.BUILD-SNAPSHOT/javadoc-api/org/springframework/context/Lifecycle.html) or [SmartLifecycle](http://docs.spring.io/spring/docs/4.1.0.BUILD-SNAPSHOT/javadoc-api/org/springframework/context/SmartLifecycle.html) – washley Aug 03 '14 at 12:36
  • Implementing a spring interface isn't in the spirit of my original answer, of course. – washley Aug 03 '14 at 12:42
  • 1
    Spring now provides the `@Async` annotation to help with this. see the documentation here: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html – kapad Jul 14 '15 at 09:44
6

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.

@Service
public class Cron {
private static Logger log = LoggerFactory.getLogger(Cron.class);

@Autowired
private PageService pageService;

@Scheduled(initialDelay = 30000, fixedDelay=120000)  // 2 minutes
public 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.

Lucas Holt
  • 3,826
  • 1
  • 32
  • 41