ScheduledAnnotationBeanPostProcessor.java 11.2 KB
Newer Older
1
/*
2
 * Copyright 2002-2013 the original author or authors.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.scheduling.annotation;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
22
import java.util.TimeZone;
C
Chris Beams 已提交
23
import java.util.concurrent.ScheduledExecutorService;
24 25 26 27

import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.config.BeanPostProcessor;
28 29
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
30
import org.springframework.context.ApplicationListener;
31
import org.springframework.context.EmbeddedValueResolverAware;
32 33 34
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.AnnotationUtils;
C
Chris Beams 已提交
35
import org.springframework.scheduling.TaskScheduler;
C
Chris Beams 已提交
36
import org.springframework.scheduling.Trigger;
37 38
import org.springframework.scheduling.config.CronTask;
import org.springframework.scheduling.config.IntervalTask;
39
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
40
import org.springframework.scheduling.support.CronTrigger;
41
import org.springframework.scheduling.support.ScheduledMethodRunnable;
42 43 44
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.ReflectionUtils.MethodCallback;
45
import org.springframework.util.StringUtils;
46
import org.springframework.util.StringValueResolver;
47 48

/**
C
Chris Beams 已提交
49
 * Bean post-processor that registers methods annotated with @{@link Scheduled}
50 51
 * to be invoked by a {@link org.springframework.scheduling.TaskScheduler} according
 * to the "fixedRate", "fixedDelay", or "cron" expression provided via the annotation.
52
 *
C
Chris Beams 已提交
53 54 55 56 57 58 59 60 61
 * <p>This post-processor is automatically registered by Spring's
 * {@code <task:annotation-driven>} XML element, and also by the @{@link EnableScheduling}
 * annotation.
 *
 * <p>Auto-detects any {@link SchedulingConfigurer} instances in the container,
 * allowing for customization of the scheduler to be used or for fine-grained control
 * over task registration (e.g. registration of {@link Trigger} tasks.
 * See @{@link EnableScheduling} Javadoc for complete usage details.
 *
62
 * @author Mark Fisher
63
 * @author Juergen Hoeller
C
Chris Beams 已提交
64
 * @author Chris Beams
65 66
 * @since 3.0
 * @see Scheduled
C
Chris Beams 已提交
67
 * @see EnableScheduling
C
Chris Beams 已提交
68
 * @see SchedulingConfigurer
69
 * @see org.springframework.scheduling.TaskScheduler
C
Chris Beams 已提交
70
 * @see org.springframework.scheduling.config.ScheduledTaskRegistrar
71
 */
72 73 74
public class ScheduledAnnotationBeanPostProcessor
		implements BeanPostProcessor, Ordered, EmbeddedValueResolverAware, ApplicationContextAware,
		ApplicationListener<ContextRefreshedEvent>, DisposableBean {
75 76 77

	private Object scheduler;

78 79
	private StringValueResolver embeddedValueResolver;

80 81
	private ApplicationContext applicationContext;

82
	private final ScheduledTaskRegistrar registrar = new ScheduledTaskRegistrar();
83 84 85


	/**
86 87 88
	 * Set the {@link org.springframework.scheduling.TaskScheduler} that will invoke
	 * the scheduled methods, or a {@link java.util.concurrent.ScheduledExecutorService}
	 * to be wrapped as a TaskScheduler.
89 90 91 92 93
	 */
	public void setScheduler(Object scheduler) {
		this.scheduler = scheduler;
	}

94
	@Override
95 96 97 98
	public void setEmbeddedValueResolver(StringValueResolver resolver) {
		this.embeddedValueResolver = resolver;
	}

99
	@Override
100 101 102 103
	public void setApplicationContext(ApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
	}

104
	@Override
105 106 107 108
	public int getOrder() {
		return LOWEST_PRECEDENCE;
	}

109
	@Override
110
	public Object postProcessBeforeInitialization(Object bean, String beanName) {
111 112 113
		return bean;
	}

114
	@Override
115
	public Object postProcessAfterInitialization(final Object bean, String beanName) {
116
		Class<?> targetClass = AopUtils.getTargetClass(bean);
117
		ReflectionUtils.doWithMethods(targetClass, new MethodCallback() {
118
			@Override
119
			public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
120 121
				for (Scheduled scheduled : AnnotationUtils.getRepeatableAnnotation(method, Schedules.class, Scheduled.class)) {
					processScheduled(scheduled, method, bean);
122 123 124 125 126 127
				}
			}
		});
		return bean;
	}

128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
	protected void processScheduled(Scheduled scheduled, Method method, Object bean) {
		try {
			Assert.isTrue(void.class.equals(method.getReturnType()),
					"Only void-returning methods may be annotated with @Scheduled");
			Assert.isTrue(method.getParameterTypes().length == 0,
					"Only no-arg methods may be annotated with @Scheduled");

			if (AopUtils.isJdkDynamicProxy(bean)) {
				try {
					// found a @Scheduled method on the target class for this JDK proxy -> is it
					// also present on the proxy itself?
					method = bean.getClass().getMethod(method.getName(), method.getParameterTypes());
				}
				catch (SecurityException ex) {
					ReflectionUtils.handleReflectionException(ex);
				}
				catch (NoSuchMethodException ex) {
					throw new IllegalStateException(String.format(
							"@Scheduled method '%s' found on bean target class '%s', " +
							"but not found in any interface(s) for bean JDK proxy. Either " +
							"pull the method up to an interface or switch to subclass (CGLIB) " +
							"proxies by setting proxy-target-class/proxyTargetClass " +
							"attribute to 'true'", method.getName(), method.getDeclaringClass().getSimpleName()));
				}
			}

			Runnable runnable = new ScheduledMethodRunnable(bean, method);
			boolean processedSchedule = false;
			String errorMessage = "Exactly one of the 'cron', 'fixedDelay(String)', or 'fixedRate(String)' attributes is required";

			// Determine initial delay
			long initialDelay = scheduled.initialDelay();
			String initialDelayString = scheduled.initialDelayString();
			if (!"".equals(initialDelayString)) {
				Assert.isTrue(initialDelay < 0, "Specify 'initialDelay' or 'initialDelayString', not both");
				if (this.embeddedValueResolver != null) {
					initialDelayString = this.embeddedValueResolver.resolveStringValue(initialDelayString);
				}
				try {
					initialDelay = Integer.parseInt(initialDelayString);
				}
				catch (NumberFormatException ex) {
					throw new IllegalArgumentException(
							"Invalid initialDelayString value \"" + initialDelayString + "\" - cannot parse into integer");
				}
			}

			// Check cron expression
			String cron = scheduled.cron();
			if (!"".equals(cron)) {
				Assert.isTrue(initialDelay == -1, "'initialDelay' not supported for cron triggers");
				processedSchedule = true;
180
				String zone = scheduled.zone();
181 182
				if (this.embeddedValueResolver != null) {
					cron = this.embeddedValueResolver.resolveStringValue(cron);
183
					zone = this.embeddedValueResolver.resolveStringValue(zone);
184
				}
185 186
				TimeZone timeZone;
				if (!"".equals(zone)) {
187
					timeZone = StringUtils.parseTimeZoneString(zone);
188 189 190 191 192
				}
				else {
					timeZone = TimeZone.getDefault();
				}
				this.registrar.addCronTask(new CronTask(runnable, new CronTrigger(cron, timeZone)));
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
			}

			// At this point we don't need to differentiate between initial delay set or not anymore
			if (initialDelay < 0) {
				initialDelay = 0;
			}

			// Check fixed delay
			long fixedDelay = scheduled.fixedDelay();
			if (fixedDelay >= 0) {
				Assert.isTrue(!processedSchedule, errorMessage);
				processedSchedule = true;
				this.registrar.addFixedDelayTask(new IntervalTask(runnable, fixedDelay, initialDelay));
			}
			String fixedDelayString = scheduled.fixedDelayString();
			if (!"".equals(fixedDelayString)) {
				Assert.isTrue(!processedSchedule, errorMessage);
				processedSchedule = true;
				if (this.embeddedValueResolver != null) {
					fixedDelayString = this.embeddedValueResolver.resolveStringValue(fixedDelayString);
				}
				try {
					fixedDelay = Integer.parseInt(fixedDelayString);
				}
				catch (NumberFormatException ex) {
					throw new IllegalArgumentException(
							"Invalid fixedDelayString value \"" + fixedDelayString + "\" - cannot parse into integer");
				}
				this.registrar.addFixedDelayTask(new IntervalTask(runnable, fixedDelay, initialDelay));
			}

			// Check fixed rate
			long fixedRate = scheduled.fixedRate();
			if (fixedRate >= 0) {
				Assert.isTrue(!processedSchedule, errorMessage);
				processedSchedule = true;
				this.registrar.addFixedRateTask(new IntervalTask(runnable, fixedRate, initialDelay));
			}
			String fixedRateString = scheduled.fixedRateString();
			if (!"".equals(fixedRateString)) {
				Assert.isTrue(!processedSchedule, errorMessage);
				processedSchedule = true;
				if (this.embeddedValueResolver != null) {
					fixedRateString = this.embeddedValueResolver.resolveStringValue(fixedRateString);
				}
				try {
					fixedRate = Integer.parseInt(fixedRateString);
				}
				catch (NumberFormatException ex) {
					throw new IllegalArgumentException(
							"Invalid fixedRateString value \"" + fixedRateString + "\" - cannot parse into integer");
				}
				this.registrar.addFixedRateTask(new IntervalTask(runnable, fixedRate, initialDelay));
			}

			// Check whether we had any attribute set
			Assert.isTrue(processedSchedule, errorMessage);
		}
		catch (IllegalArgumentException ex) {
			throw new IllegalStateException(
					"Encountered invalid @Scheduled method '" + method.getName() + "': " + ex.getMessage());
		}
	}

257
	@Override
258
	public void onApplicationEvent(ContextRefreshedEvent event) {
C
Chris Beams 已提交
259 260 261
		if (event.getApplicationContext() != this.applicationContext) {
			return;
		}
262

C
Chris Beams 已提交
263 264 265
		if (this.scheduler != null) {
			this.registrar.setScheduler(this.scheduler);
		}
266 267 268

		Map<String, SchedulingConfigurer> configurers =
				this.applicationContext.getBeansOfType(SchedulingConfigurer.class);
C
Chris Beams 已提交
269 270 271
		for (SchedulingConfigurer configurer : configurers.values()) {
			configurer.configureTasks(this.registrar);
		}
272

273
		if (this.registrar.hasTasks() && this.registrar.getScheduler() == null) {
C
Chris Beams 已提交
274
			Map<String, ? super Object> schedulers = new HashMap<String, Object>();
275 276
			schedulers.putAll(this.applicationContext.getBeansOfType(TaskScheduler.class));
			schedulers.putAll(this.applicationContext.getBeansOfType(ScheduledExecutorService.class));
C
Chris Beams 已提交
277 278
			if (schedulers.size() == 0) {
				// do nothing -> fall back to default scheduler
279 280
			}
			else if (schedulers.size() == 1) {
C
Chris Beams 已提交
281
				this.registrar.setScheduler(schedulers.values().iterator().next());
282 283 284 285 286 287 288 289
			}
			else if (schedulers.size() >= 2){
				throw new IllegalStateException(
						"More than one TaskScheduler and/or ScheduledExecutorService  " +
						"exist within the context. Remove all but one of the beans; or " +
						"implement the SchedulingConfigurer interface and call " +
						"ScheduledTaskRegistrar#setScheduler explicitly within the " +
						"configureTasks() callback. Found the following beans: " + schedulers.keySet());
290
			}
291
		}
292

C
Chris Beams 已提交
293
		this.registrar.afterPropertiesSet();
294 295
	}

296
	@Override
297 298
	public void destroy() {
		this.registrar.destroy();
299 300 301
	}

}