|
| 1 | +/* |
| 2 | + * Copyright 2002-2013 the original author or authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package org.springframework.scheduling.config; |
| 18 | + |
| 19 | +import org.springframework.context.ApplicationContext; |
| 20 | +import org.springframework.context.ApplicationContextAware; |
| 21 | +import org.springframework.context.ApplicationListener; |
| 22 | +import org.springframework.context.event.ContextRefreshedEvent; |
| 23 | + |
| 24 | +/** |
| 25 | + * {@link ScheduledTaskRegistrar} subclass that redirect the actual scheduling |
| 26 | + * of tasks to the {@link ContextRefreshedEvent} callback. Falls back to regular |
| 27 | + * {@link ScheduledTaskRegistrar} behavior when not running within an ApplicationContext. |
| 28 | + * |
| 29 | + * @author Juergen Hoeller |
| 30 | + * @since 3.2.1 |
| 31 | + */ |
| 32 | +public class ContextLifecycleScheduledTaskRegistrar extends ScheduledTaskRegistrar |
| 33 | + implements ApplicationContextAware, ApplicationListener<ContextRefreshedEvent> { |
| 34 | + |
| 35 | + private ApplicationContext applicationContext; |
| 36 | + |
| 37 | + |
| 38 | + public void setApplicationContext(ApplicationContext applicationContext) { |
| 39 | + this.applicationContext = applicationContext; |
| 40 | + } |
| 41 | + |
| 42 | + |
| 43 | + /** |
| 44 | + * If we're running within an ApplicationContext, don't schedule the tasks |
| 45 | + * right here; wait for this context's ContextRefreshedEvent instead. |
| 46 | + */ |
| 47 | + @Override |
| 48 | + public void afterPropertiesSet() { |
| 49 | + if (this.applicationContext == null) { |
| 50 | + scheduleTasks(); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * Actually schedule the tasks at the right time of the context lifecycle, |
| 56 | + * if we're running within an ApplicationContext. |
| 57 | + */ |
| 58 | + public void onApplicationEvent(ContextRefreshedEvent event) { |
| 59 | + if (event.getApplicationContext() != this.applicationContext) { |
| 60 | + return; |
| 61 | + } |
| 62 | + scheduleTasks(); |
| 63 | + } |
| 64 | + |
| 65 | +} |
0 commit comments