spring 独立应用程序中的预定方法 [英] Scheduled method in a standalone application in spring

查看:48
本文介绍了spring 独立应用程序中的预定方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法需要每天 07:00 执行.为此,我使用该方法创建了一个 bean,并使用 @Scheduled(cron="0 0 7 * * ?") 对其进行了注释.在这个 bean 中,我创建了一个 main 函数 - 它将初始化 spring 上下文,获取 bean 并调用该方法(至少是第一次),如下所示:

I have a method which needs to be executed every day at 07:00. For that matter I created a bean with the method and annotated it with @Scheduled(cron="0 0 7 * * ?"). In this bean I crated a main function - which will initialize the spring context, get the bean and invoke the method ( at least for the first time ), like this:

public static void main(String[] args) {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(args[0]);
    SchedulerService schedulerService = context.getBean(SchedulerService.class);
    schedulerService.myMethod();
}

这很好用 - 但只有一次.我想我明白为什么 - 这是因为 main 线程结束 - Spring 上下文也是如此,即使 myMethod@Scheduled 注释它行不通.

This works just fine - but just once. I think I understand why - It's because the main thread ends - and so is the spring context so even though myMethod is annotated with @Scheduled it wont work.

我想到了一种方法来传递这个 - 意思是不要让 main 线程死,也许像这样:

I thought of a way to pass this - meaning don't let the main thread die, perhaps like this:

while (true){
   Thread.currentThread().sleep(500);
}

我认为这就是应用程序上下文将保留的方式,我的 bean 也是如此.

That's how, I think, the application context will remain and so is my bean.

我说得对吗?

有没有更好的方法来解决这个问题?

Is there a better way to solve this?

我使用的是 spring 3.1.2.

I'm using spring 3.1.2.

谢谢.

推荐答案

主线程应该保持活动状态,直到任何非守护线程处于活动状态.如果您的应用程序中有 <task:annotation-driven/> 标记,那么 Spring 应该为您启动一个带有一小部分非守护线程池的执行程序,并且主应用程序不应终止.

The main thread should stay active until any non-daemon threads are alive. If you have a <task:annotation-driven/> tag in your application then Spring should start up a executor with a small pool of non-daemon threads for you and the main application should not terminate.

您唯一需要做的就是注册一个关闭钩子,以确保在 VM 结束时进行清理.

The only thing that you will need to do is to register a shutdown hook also to ensure a cleanup when the VM ends.

context.registerShutdownHook()

这篇关于spring 独立应用程序中的预定方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆