大家好,又见面了,我是你们的朋友全栈君。
spring管理quartz生命周期之SchedulerFactoryBean
spring通过SchedulerFactoryBean
来管理quartz的生命周期。在spring容器启动时启动调度器,在spring容器关闭时停止调度器
FactoryBeanthat creates and configures a Quartz {@link org.quartz.Scheduler},manages its lifecycle as part of the Spring application context, and exposes the Scheduler as bean reference for dependency injection.
为了防止启动失败,我们可以通过实现ApplicationListener
接口来手动判断定时任务调试器是否启动,若没有启动,可以再次启动:
@Component("quartzStarterListener")
public class QuartzStarterListener implements ApplicationListener {
private static final Logger LOGGER = LoggerFactory.getLogger(QuartzStarterListener.class);
private boolean started = false;
@Autowired
private Scheduler scheduler;
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ContextRefreshedEvent){
LOGGER.info("trying to refresh.>>>>>>>>>");
try {
if (!started && !scheduler.isStarted()){
started = true;
LOGGER.info("trying to start quartz.>>>>>>>>");
scheduler.start();
LOGGER.info("quartz has been started.>>>>>>>>");
}
} catch (SchedulerException e) {
LOGGER.error("error occurred when starting quartz.>>>>>>>>", e);
e.printStackTrace();
}
}else if (event instanceof ContextClosedEvent ||
event instanceof ContextStoppedEvent){
try {
if (scheduler.isStarted()){
//等待所有定时任务执行完毕才停止
scheduler.shutdown(true);
LOGGER.info("quartz has been stopped.>>>>>>");
}
} catch (SchedulerException e) {
LOGGER.error("error occurred when stopping quartz.>>>>>>>", e);
e.printStackTrace();
}
}
}
}
结果:
[2018-08-16 10:47:03.924] [ INFO] QuartzStarterListener trying to refresh.>>>>>>>>>
16-Aug-2018 10:47:03.929 信息 [RMI TCP Connection(5)-127.0.0.1] org.springframework.web.servlet.DispatcherServlet.initServletBean
FrameworkServlet 'springDispatcherServlet': initialization completed in 1947 ms
[2018-08-16 10:47:03,963] Artifact ssm:war exploded: Artifact is deployed successfully
[2018-08-16 10:47:03,963] Artifact ssm:war exploded: Deploy took 12,434 milliseconds
...
[2018-08-16 10:47:06.506] [ INFO] QuartzScheduler Scheduler scheduler_$_NON_CLUSTERED shutdown complete.
[2018-08-16 10:47:06.506] [ INFO] QuartzStarterListener quartz has been stopped.>>>>>>
[2018-08-16 10:47:06.518] [ INFO] QuartzStarterListener quartz has been stopped.>>>>>>
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/142515.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...