我有一个方法需要每天07:00执行。
就此而言,我使用该方法创建了一个bean,并使用@Scheduled(cron="0 0 7 * * ?")
对其进行了注释。
在这个bean中,我创建了一个main
函数 - 它将初始化spring上下文,获取bean并调用该方法(至少是第一次),如下所示:
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(args[0]);
SchedulerService schedulerService = context.getBean(SchedulerService.class);
schedulerService.myMethod();
}
这很好 - 但只有一次。
我想我理解为什么 - 这是因为main
线程结束 - 春天上下文也是如此,所以即使myMethod
注释了@Scheduled
它也无法工作。
我想到了一种方法来传递这个 - 意思是不要让main
线程死掉,也许是这样:
while (true){
Thread.currentThread().sleep(500);
}
我认为,应用程序上下文将保留,我的bean也是如此。
我是对的吗?
有没有更好的方法来解决这个问题?
我正在使用spring 3.1.2。
感谢。
答案 0 :(得分:4)
主线程应保持活动状态,直到任何非守护程序线程处于活动状态。如果您的应用程序中有<task:annotation-driven/>
标记,那么Spring应该为您启动一个带有少量非守护程序线程的执行程序,并且主应用程序不应该终止。
您唯一需要做的就是注册一个关闭钩子,以确保在VM结束时进行清理。
context.registerShutdownHook()
答案 1 :(得分:1)
连接方法非常适用于此:
try {
Thread.currentThread().join();
} catch (InterruptedException e) {
logger.warn("Interrupted", e);
}
或者,这是旧学校的等待方法:
final Object sync = new Object();
synchronized (sync) {
try {
sync.wait();
} catch (InterruptedException e) {
logger.warn("Interrupted", e);
}
}