且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查@Schedule批注(Spring 3.1)cron作业是否正在运行.

更新时间:2023-12-05 11:59:04

我的问题是我可以在@Schedule上放一些支票或看门人吗cron作业是否知道它是否正在运行?

my question is that can I put some check or watcher on the @Schedule cron job to know whether it is running or not ?

基本上,您不能.

当您使用 @Scheduled 时,Spring使用 ScheduledAnnotationBeanPostProcessor 来注册您指定的任务(带注释的方法).它使用 ScheduledTaskRegistrar 注册它们. ScheduledAnnotationBeanPostProcessor ApplicationListener< ContextRefreshEvent> .当它从 ApplicationContext 接收到 ContextRefreshEvent 时,它将调度在 ScheduledTaskRegistrar 中注册的任务.

When you use @Scheduled, Spring uses a ScheduledAnnotationBeanPostProcessor to register the tasks you specify (annotated methods). It registers them with a ScheduledTaskRegistrar. The ScheduledAnnotationBeanPostProcessor is an ApplicationListener<ContextRefreshEvent>. When it receives the ContextRefreshEvent from the ApplicationContext, it schedules the tasks registered in the ScheduledTaskRegistrar.

在此步骤中,这些任务是通过 TaskScheduler 安排的,该任务通常包装 ScheduledExecutorService .如果发生异常未被提交的任务捕获,然后将该任务从 ScheduledExecutorService 队列中删除.

During this step, these tasks are scheduled with a TaskScheduler which typically wraps a ScheduledExecutorService. If an exception is uncaught in a submitted task, then the task is removed from the ScheduledExecutorService queue.

TaskScheduler 类不提供公共API来检索计划的任务,即. ScheduledFuture 对象.因此,您无法使用它来确定您的任务是否正在运行.

The TaskScheduler class does not provide a public API to retrieve the scheduled tasks, ie. the ScheduledFuture objects. So you can't use it to find out if your tasks are running or not.

您可能不应该这样做.开发您的任务和您的 @Scheduled 方法,以能够承受所引发的异常.有时候,这显然是不可能的.例如,由于网络错误,您可能必须重新启动应用程序.在不了解您的应用程序的情况下,我想说更多日志记录是您的***选择.

And you probably shouldn't. Develop your tasks, your @Scheduled methods, to be able to withstand an exception being thrown. Some times, obviously, that's not possible. With a network error, for example, you would probably have to restart your application. Without knowing anything else about your application, I would say more logging is your best bet.