001/*
002 * Copyright 2002-2017 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.scheduling.concurrent;
018
019import java.util.Date;
020import java.util.concurrent.Executor;
021import java.util.concurrent.Executors;
022import java.util.concurrent.RejectedExecutionException;
023import java.util.concurrent.ScheduledExecutorService;
024import java.util.concurrent.ScheduledFuture;
025import java.util.concurrent.TimeUnit;
026import javax.enterprise.concurrent.LastExecution;
027import javax.enterprise.concurrent.ManagedScheduledExecutorService;
028
029import org.springframework.core.task.TaskRejectedException;
030import org.springframework.scheduling.TaskScheduler;
031import org.springframework.scheduling.Trigger;
032import org.springframework.scheduling.support.SimpleTriggerContext;
033import org.springframework.scheduling.support.TaskUtils;
034import org.springframework.util.Assert;
035import org.springframework.util.ClassUtils;
036import org.springframework.util.ErrorHandler;
037
038/**
039 * Adapter that takes a {@code java.util.concurrent.ScheduledExecutorService} and
040 * exposes a Spring {@link org.springframework.scheduling.TaskScheduler} for it.
041 * Extends {@link ConcurrentTaskExecutor} in order to implement the
042 * {@link org.springframework.scheduling.SchedulingTaskExecutor} interface as well.
043 *
044 * <p>Autodetects a JSR-236 {@link javax.enterprise.concurrent.ManagedScheduledExecutorService}
045 * in order to use it for trigger-based scheduling if possible, instead of Spring's
046 * local trigger management which ends up delegating to regular delay-based scheduling
047 * against the {@code java.util.concurrent.ScheduledExecutorService} API. For JSR-236 style
048 * lookup in a Java EE 7 environment, consider using {@link DefaultManagedTaskScheduler}.
049 *
050 * <p>Note that there is a pre-built {@link ThreadPoolTaskScheduler} that allows for
051 * defining a {@link java.util.concurrent.ScheduledThreadPoolExecutor} in bean style,
052 * exposing it as a Spring {@link org.springframework.scheduling.TaskScheduler} directly.
053 * This is a convenient alternative to a raw ScheduledThreadPoolExecutor definition with
054 * a separate definition of the present adapter class.
055 *
056 * @author Juergen Hoeller
057 * @author Mark Fisher
058 * @since 3.0
059 * @see java.util.concurrent.ScheduledExecutorService
060 * @see java.util.concurrent.ScheduledThreadPoolExecutor
061 * @see java.util.concurrent.Executors
062 * @see DefaultManagedTaskScheduler
063 * @see ThreadPoolTaskScheduler
064 */
065public class ConcurrentTaskScheduler extends ConcurrentTaskExecutor implements TaskScheduler {
066
067        private static Class<?> managedScheduledExecutorServiceClass;
068
069        static {
070                try {
071                        managedScheduledExecutorServiceClass = ClassUtils.forName(
072                                        "javax.enterprise.concurrent.ManagedScheduledExecutorService",
073                                        ConcurrentTaskScheduler.class.getClassLoader());
074                }
075                catch (ClassNotFoundException ex) {
076                        // JSR-236 API not available...
077                        managedScheduledExecutorServiceClass = null;
078                }
079        }
080
081        private ScheduledExecutorService scheduledExecutor;
082
083        private boolean enterpriseConcurrentScheduler = false;
084
085        private ErrorHandler errorHandler;
086
087
088        /**
089         * Create a new ConcurrentTaskScheduler,
090         * using a single thread executor as default.
091         * @see java.util.concurrent.Executors#newSingleThreadScheduledExecutor()
092         */
093        public ConcurrentTaskScheduler() {
094                super();
095                setScheduledExecutor(null);
096        }
097
098        /**
099         * Create a new ConcurrentTaskScheduler, using the given
100         * {@link java.util.concurrent.ScheduledExecutorService} as shared delegate.
101         * <p>Autodetects a JSR-236 {@link javax.enterprise.concurrent.ManagedScheduledExecutorService}
102         * in order to use it for trigger-based scheduling if possible,
103         * instead of Spring's local trigger management.
104         * @param scheduledExecutor the {@link java.util.concurrent.ScheduledExecutorService}
105         * to delegate to for {@link org.springframework.scheduling.SchedulingTaskExecutor}
106         * as well as {@link TaskScheduler} invocations
107         */
108        public ConcurrentTaskScheduler(ScheduledExecutorService scheduledExecutor) {
109                super(scheduledExecutor);
110                setScheduledExecutor(scheduledExecutor);
111        }
112
113        /**
114         * Create a new ConcurrentTaskScheduler, using the given {@link java.util.concurrent.Executor}
115         * and {@link java.util.concurrent.ScheduledExecutorService} as delegates.
116         * <p>Autodetects a JSR-236 {@link javax.enterprise.concurrent.ManagedScheduledExecutorService}
117         * in order to use it for trigger-based scheduling if possible,
118         * instead of Spring's local trigger management.
119         * @param concurrentExecutor the {@link java.util.concurrent.Executor} to delegate to
120         * for {@link org.springframework.scheduling.SchedulingTaskExecutor} invocations
121         * @param scheduledExecutor the {@link java.util.concurrent.ScheduledExecutorService}
122         * to delegate to for {@link TaskScheduler} invocations
123         */
124        public ConcurrentTaskScheduler(Executor concurrentExecutor, ScheduledExecutorService scheduledExecutor) {
125                super(concurrentExecutor);
126                setScheduledExecutor(scheduledExecutor);
127        }
128
129
130        /**
131         * Specify the {@link java.util.concurrent.ScheduledExecutorService} to delegate to.
132         * <p>Autodetects a JSR-236 {@link javax.enterprise.concurrent.ManagedScheduledExecutorService}
133         * in order to use it for trigger-based scheduling if possible,
134         * instead of Spring's local trigger management.
135         * <p>Note: This will only apply to {@link TaskScheduler} invocations.
136         * If you want the given executor to apply to
137         * {@link org.springframework.scheduling.SchedulingTaskExecutor} invocations
138         * as well, pass the same executor reference to {@link #setConcurrentExecutor}.
139         * @see #setConcurrentExecutor
140         */
141        public final void setScheduledExecutor(ScheduledExecutorService scheduledExecutor) {
142                if (scheduledExecutor != null) {
143                        this.scheduledExecutor = scheduledExecutor;
144                        this.enterpriseConcurrentScheduler = (managedScheduledExecutorServiceClass != null &&
145                                        managedScheduledExecutorServiceClass.isInstance(scheduledExecutor));
146                }
147                else {
148                        this.scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
149                        this.enterpriseConcurrentScheduler = false;
150                }
151        }
152
153        /**
154         * Provide an {@link ErrorHandler} strategy.
155         */
156        public void setErrorHandler(ErrorHandler errorHandler) {
157                Assert.notNull(errorHandler, "ErrorHandler must not be null");
158                this.errorHandler = errorHandler;
159        }
160
161
162        @Override
163        public ScheduledFuture<?> schedule(Runnable task, Trigger trigger) {
164                try {
165                        if (this.enterpriseConcurrentScheduler) {
166                                return new EnterpriseConcurrentTriggerScheduler().schedule(decorateTask(task, true), trigger);
167                        }
168                        else {
169                                ErrorHandler errorHandler =
170                                                (this.errorHandler != null ? this.errorHandler : TaskUtils.getDefaultErrorHandler(true));
171                                return new ReschedulingRunnable(task, trigger, this.scheduledExecutor, errorHandler).schedule();
172                        }
173                }
174                catch (RejectedExecutionException ex) {
175                        throw new TaskRejectedException("Executor [" + this.scheduledExecutor + "] did not accept task: " + task, ex);
176                }
177        }
178
179        @Override
180        public ScheduledFuture<?> schedule(Runnable task, Date startTime) {
181                long initialDelay = startTime.getTime() - System.currentTimeMillis();
182                try {
183                        return this.scheduledExecutor.schedule(decorateTask(task, false), initialDelay, TimeUnit.MILLISECONDS);
184                }
185                catch (RejectedExecutionException ex) {
186                        throw new TaskRejectedException("Executor [" + this.scheduledExecutor + "] did not accept task: " + task, ex);
187                }
188        }
189
190        @Override
191        public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Date startTime, long period) {
192                long initialDelay = startTime.getTime() - System.currentTimeMillis();
193                try {
194                        return this.scheduledExecutor.scheduleAtFixedRate(decorateTask(task, true), initialDelay, period, TimeUnit.MILLISECONDS);
195                }
196                catch (RejectedExecutionException ex) {
197                        throw new TaskRejectedException("Executor [" + this.scheduledExecutor + "] did not accept task: " + task, ex);
198                }
199        }
200
201        @Override
202        public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long period) {
203                try {
204                        return this.scheduledExecutor.scheduleAtFixedRate(decorateTask(task, true), 0, period, TimeUnit.MILLISECONDS);
205                }
206                catch (RejectedExecutionException ex) {
207                        throw new TaskRejectedException("Executor [" + this.scheduledExecutor + "] did not accept task: " + task, ex);
208                }
209        }
210
211        @Override
212        public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Date startTime, long delay) {
213                long initialDelay = startTime.getTime() - System.currentTimeMillis();
214                try {
215                        return this.scheduledExecutor.scheduleWithFixedDelay(decorateTask(task, true), initialDelay, delay, TimeUnit.MILLISECONDS);
216                }
217                catch (RejectedExecutionException ex) {
218                        throw new TaskRejectedException("Executor [" + this.scheduledExecutor + "] did not accept task: " + task, ex);
219                }
220        }
221
222        @Override
223        public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, long delay) {
224                try {
225                        return this.scheduledExecutor.scheduleWithFixedDelay(decorateTask(task, true), 0, delay, TimeUnit.MILLISECONDS);
226                }
227                catch (RejectedExecutionException ex) {
228                        throw new TaskRejectedException("Executor [" + this.scheduledExecutor + "] did not accept task: " + task, ex);
229                }
230        }
231
232        private Runnable decorateTask(Runnable task, boolean isRepeatingTask) {
233                Runnable result = TaskUtils.decorateTaskWithErrorHandler(task, this.errorHandler, isRepeatingTask);
234                if (this.enterpriseConcurrentScheduler) {
235                        result = ManagedTaskBuilder.buildManagedTask(result, task.toString());
236                }
237                return result;
238        }
239
240
241        /**
242         * Delegate that adapts a Spring Trigger to a JSR-236 Trigger.
243         * Separated into an inner class in order to avoid a hard dependency on the JSR-236 API.
244         */
245        private class EnterpriseConcurrentTriggerScheduler {
246
247                public ScheduledFuture<?> schedule(Runnable task, final Trigger trigger) {
248                        ManagedScheduledExecutorService executor = (ManagedScheduledExecutorService) scheduledExecutor;
249                        return executor.schedule(task, new javax.enterprise.concurrent.Trigger() {
250                                @Override
251                                public Date getNextRunTime(LastExecution le, Date taskScheduledTime) {
252                                        return (trigger.nextExecutionTime(le != null ?
253                                                        new SimpleTriggerContext(le.getScheduledStart(), le.getRunStart(), le.getRunEnd()) :
254                                                        new SimpleTriggerContext()));
255                                }
256                                @Override
257                                public boolean skipRun(LastExecution lastExecution, Date scheduledRunTime) {
258                                        return false;
259                                }
260                        });
261                }
262        }
263
264}