如何在spring webapp中创建后台进程?
我想与我的 spring-mvc Web 应用程序并行运行后台进程。我需要一种在上下文加载时自动启动的方法。后台进程是一个实现Runnable
的类。 spring-mvc 有一些工具吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Spring有一个全面的任务执行框架。请参阅文档的相关部分 。
我建议在您的上下文中使用 Spring bean,它在初始化时将您的后台 Runnable 提交给
SimpleAsyncTaskExecutor
bean。这是最简单的方法,您可以根据需要使其变得更加复杂和强大。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 aSimpleAsyncTaskExecutor
bean. That's the simplest approach, which you can make more complex and capable as you see fit.我会继续查看 skaffman 链接的任务调度文档,但是如果您真正想做的只是在上下文初始化时启动后台线程,那么还有一种更简单的方法。
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.
作为另一种选择,现在可以使用 Spring 的调度功能。在 Spring 3 或更高版本中,它具有类似 cron 的注释,允许您使用方法的简单注释来安排任务运行。它对于自动装配也很友好。
此示例每 2 分钟安排一个任务,初始等待(启动时)为 30 秒。下一个任务将在该方法完成后 2 分钟运行!如果您希望它精确地每 2 分钟运行一次,请改用fixedInterval。
请务必添加@EnableAsync
@EnableScheduling 到您的 Application 类以启用此功能。
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.
Be sure to also add @EnableAsync
@EnableScheduling to your Application class to enable this feature.