如何在spring webapp中创建后台进程?

Vla*_*mir 18 java spring multithreading background-process

我想与spring-mvc web应用程序并行运行后台进程.我需要一种方法来自动启动上下文加载.后台进程是一个实现的类Runnable.spring-mvc有一些设施吗?

ska*_*man 17

Spring有一个全面的任务执行框架.请参阅文档相关部分.

我建议在你的上下文中使用一个Spring bean,在初始化时,将你的背景提交RunnableSimpleAsyncTaskExecutorbean.这是最简单的方法,您可以根据自己的需要使其更加复杂和有能力.


小智 7

我会继续看看由skaffman链接的任务调度文档,但如果您真正想要做的就是在上下文初始化时启动后台线程,那么还有一种更简单的方法.

<bean id="myRunnableThingy">
  ...
</bean>

<bean id="thingyThread" class="java.lang.Thread" init-method="start">
  <constructor-arg ref="myRunnableThingy"/>
</bean>
Run Code Online (Sandbox Code Playgroud)


Luc*_*olt 6

作为另一种选择,现在可以使用 Spring 的调度功能。在 Spring 3 或更高版本中,它有一个类似 cron 的注释,允许您使用简单的方法注释来安排任务运行。它对自动装配也很友好。

此示例每 2 分钟安排一个任务,初始等待(启动时)为 30 秒。下一个任务将在方法完成后 2 分钟运行!如果您希望它恰好每 2 分钟运行一次,请改用 fixedInterval。

@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());
    }
}

}
Run Code Online (Sandbox Code Playgroud)

确保还将 @EnableAsync @EnableScheduling 添加到您的 Application 类以启用此功能。