-
Notifications
You must be signed in to change notification settings - Fork 37.7k
/
ScheduledTaskRegistrar.java
493 lines (441 loc) · 15.1 KB
/
ScheduledTaskRegistrar.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
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
180
181
182
183
184
185
186
187
188
189
190
191
192
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
/*
* Copyright 2002-2016 the original author or authors.
*
* 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
*
* https://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.config;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
/**
* Helper bean for registering tasks with a {@link TaskScheduler}, typically using cron
* expressions.
*
* <p>As of Spring 3.1, {@code ScheduledTaskRegistrar} has a more prominent user-facing
* role when used in conjunction with the @{@link
* org.springframework.scheduling.annotation.EnableAsync EnableAsync} annotation and its
* {@link org.springframework.scheduling.annotation.SchedulingConfigurer
* SchedulingConfigurer} callback interface.
*
* @author Juergen Hoeller
* @author Chris Beams
* @author Tobias Montagna-Hay
* @since 3.0
* @see org.springframework.scheduling.annotation.EnableAsync
* @see org.springframework.scheduling.annotation.SchedulingConfigurer
*/
public class ScheduledTaskRegistrar implements InitializingBean, DisposableBean {
private TaskScheduler taskScheduler;
private ScheduledExecutorService localExecutor;
private List<TriggerTask> triggerTasks;
private List<CronTask> cronTasks;
private List<IntervalTask> fixedRateTasks;
private List<IntervalTask> fixedDelayTasks;
private final Map<Task, ScheduledTask> unresolvedTasks = new HashMap<Task, ScheduledTask>(16);
private final Set<ScheduledTask> scheduledTasks = new LinkedHashSet<ScheduledTask>(16);
/**
* Set the {@link TaskScheduler} to register scheduled tasks with.
*/
public void setTaskScheduler(TaskScheduler taskScheduler) {
Assert.notNull(taskScheduler, "TaskScheduler must not be null");
this.taskScheduler = taskScheduler;
}
/**
* Set the {@link TaskScheduler} to register scheduled tasks with, or a
* {@link java.util.concurrent.ScheduledExecutorService} to be wrapped as a
* {@code TaskScheduler}.
*/
public void setScheduler(Object scheduler) {
Assert.notNull(scheduler, "Scheduler object must not be null");
if (scheduler instanceof TaskScheduler) {
this.taskScheduler = (TaskScheduler) scheduler;
}
else if (scheduler instanceof ScheduledExecutorService) {
this.taskScheduler = new ConcurrentTaskScheduler(((ScheduledExecutorService) scheduler));
}
else {
throw new IllegalArgumentException("Unsupported scheduler type: " + scheduler.getClass());
}
}
/**
* Return the {@link TaskScheduler} instance for this registrar (may be {@code null}).
*/
public TaskScheduler getScheduler() {
return this.taskScheduler;
}
/**
* Specify triggered tasks as a Map of Runnables (the tasks) and Trigger objects
* (typically custom implementations of the {@link Trigger} interface).
*/
public void setTriggerTasks(Map<Runnable, Trigger> triggerTasks) {
this.triggerTasks = new ArrayList<TriggerTask>();
for (Map.Entry<Runnable, Trigger> task : triggerTasks.entrySet()) {
addTriggerTask(new TriggerTask(task.getKey(), task.getValue()));
}
}
/**
* Specify triggered tasks as a list of {@link TriggerTask} objects. Primarily used
* by {@code <task:*>} namespace parsing.
* @since 3.2
* @see ScheduledTasksBeanDefinitionParser
*/
public void setTriggerTasksList(List<TriggerTask> triggerTasks) {
this.triggerTasks = triggerTasks;
}
/**
* Get the trigger tasks as an unmodifiable list of {@link TriggerTask} objects.
* @return the list of tasks (never {@code null})
* @since 4.2
*/
public List<TriggerTask> getTriggerTaskList() {
return (this.triggerTasks != null? Collections.unmodifiableList(this.triggerTasks) :
Collections.<TriggerTask>emptyList());
}
/**
* Specify triggered tasks as a Map of Runnables (the tasks) and cron expressions.
* @see CronTrigger
*/
public void setCronTasks(Map<Runnable, String> cronTasks) {
this.cronTasks = new ArrayList<CronTask>();
for (Map.Entry<Runnable, String> task : cronTasks.entrySet()) {
addCronTask(task.getKey(), task.getValue());
}
}
/**
* Specify triggered tasks as a list of {@link CronTask} objects. Primarily used by
* {@code <task:*>} namespace parsing.
* @since 3.2
* @see ScheduledTasksBeanDefinitionParser
*/
public void setCronTasksList(List<CronTask> cronTasks) {
this.cronTasks = cronTasks;
}
/**
* Get the cron tasks as an unmodifiable list of {@link CronTask} objects.
* @return the list of tasks (never {@code null})
* @since 4.2
*/
public List<CronTask> getCronTaskList() {
return (this.cronTasks != null ? Collections.unmodifiableList(this.cronTasks) :
Collections.<CronTask>emptyList());
}
/**
* Specify triggered tasks as a Map of Runnables (the tasks) and fixed-rate values.
* @see TaskScheduler#scheduleAtFixedRate(Runnable, long)
*/
public void setFixedRateTasks(Map<Runnable, Long> fixedRateTasks) {
this.fixedRateTasks = new ArrayList<IntervalTask>();
for (Map.Entry<Runnable, Long> task : fixedRateTasks.entrySet()) {
addFixedRateTask(task.getKey(), task.getValue());
}
}
/**
* Specify fixed-rate tasks as a list of {@link IntervalTask} objects. Primarily used
* by {@code <task:*>} namespace parsing.
* @since 3.2
* @see ScheduledTasksBeanDefinitionParser
*/
public void setFixedRateTasksList(List<IntervalTask> fixedRateTasks) {
this.fixedRateTasks = fixedRateTasks;
}
/**
* Get the fixed-rate tasks as an unmodifiable list of {@link IntervalTask} objects.
* @return the list of tasks (never {@code null})
* @since 4.2
*/
public List<IntervalTask> getFixedRateTaskList() {
return (this.fixedRateTasks != null ? Collections.unmodifiableList(this.fixedRateTasks) :
Collections.<IntervalTask>emptyList());
}
/**
* Specify triggered tasks as a Map of Runnables (the tasks) and fixed-delay values.
* @see TaskScheduler#scheduleWithFixedDelay(Runnable, long)
*/
public void setFixedDelayTasks(Map<Runnable, Long> fixedDelayTasks) {
this.fixedDelayTasks = new ArrayList<IntervalTask>();
for (Map.Entry<Runnable, Long> task : fixedDelayTasks.entrySet()) {
addFixedDelayTask(task.getKey(), task.getValue());
}
}
/**
* Specify fixed-delay tasks as a list of {@link IntervalTask} objects. Primarily used
* by {@code <task:*>} namespace parsing.
* @since 3.2
* @see ScheduledTasksBeanDefinitionParser
*/
public void setFixedDelayTasksList(List<IntervalTask> fixedDelayTasks) {
this.fixedDelayTasks = fixedDelayTasks;
}
/**
* Get the fixed-delay tasks as an unmodifiable list of {@link IntervalTask} objects.
* @return the list of tasks (never {@code null})
* @since 4.2
*/
public List<IntervalTask> getFixedDelayTaskList() {
return (this.fixedDelayTasks != null ? Collections.unmodifiableList(this.fixedDelayTasks) :
Collections.<IntervalTask>emptyList());
}
/**
* Add a Runnable task to be triggered per the given {@link Trigger}.
* @see TaskScheduler#scheduleAtFixedRate(Runnable, long)
*/
public void addTriggerTask(Runnable task, Trigger trigger) {
addTriggerTask(new TriggerTask(task, trigger));
}
/**
* Add a {@code TriggerTask}.
* @since 3.2
* @see TaskScheduler#scheduleAtFixedRate(Runnable, long)
*/
public void addTriggerTask(TriggerTask task) {
if (this.triggerTasks == null) {
this.triggerTasks = new ArrayList<TriggerTask>();
}
this.triggerTasks.add(task);
}
/**
* Add a Runnable task to be triggered per the given cron expression
*/
public void addCronTask(Runnable task, String expression) {
addCronTask(new CronTask(task, expression));
}
/**
* Add a {@link CronTask}.
* @since 3.2
*/
public void addCronTask(CronTask task) {
if (this.cronTasks == null) {
this.cronTasks = new ArrayList<CronTask>();
}
this.cronTasks.add(task);
}
/**
* Add a {@code Runnable} task to be triggered at the given fixed-rate interval.
* @see TaskScheduler#scheduleAtFixedRate(Runnable, long)
*/
public void addFixedRateTask(Runnable task, long interval) {
addFixedRateTask(new IntervalTask(task, interval, 0));
}
/**
* Add a fixed-rate {@link IntervalTask}.
* @since 3.2
* @see TaskScheduler#scheduleAtFixedRate(Runnable, long)
*/
public void addFixedRateTask(IntervalTask task) {
if (this.fixedRateTasks == null) {
this.fixedRateTasks = new ArrayList<IntervalTask>();
}
this.fixedRateTasks.add(task);
}
/**
* Add a Runnable task to be triggered with the given fixed delay.
* @see TaskScheduler#scheduleWithFixedDelay(Runnable, long)
*/
public void addFixedDelayTask(Runnable task, long delay) {
addFixedDelayTask(new IntervalTask(task, delay, 0));
}
/**
* Add a fixed-delay {@link IntervalTask}.
* @since 3.2
* @see TaskScheduler#scheduleWithFixedDelay(Runnable, long)
*/
public void addFixedDelayTask(IntervalTask task) {
if (this.fixedDelayTasks == null) {
this.fixedDelayTasks = new ArrayList<IntervalTask>();
}
this.fixedDelayTasks.add(task);
}
/**
* Return whether this {@code ScheduledTaskRegistrar} has any tasks registered.
* @since 3.2
*/
public boolean hasTasks() {
return (!CollectionUtils.isEmpty(this.triggerTasks) ||
!CollectionUtils.isEmpty(this.cronTasks) ||
!CollectionUtils.isEmpty(this.fixedRateTasks) ||
!CollectionUtils.isEmpty(this.fixedDelayTasks));
}
/**
* Calls {@link #scheduleTasks()} at bean construction time.
*/
@Override
public void afterPropertiesSet() {
scheduleTasks();
}
/**
* Schedule all registered tasks against the underlying {@linkplain
* #setTaskScheduler(TaskScheduler) task scheduler}.
*/
protected void scheduleTasks() {
if (this.taskScheduler == null) {
this.localExecutor = Executors.newSingleThreadScheduledExecutor();
this.taskScheduler = new ConcurrentTaskScheduler(this.localExecutor);
}
if (this.triggerTasks != null) {
for (TriggerTask task : this.triggerTasks) {
addScheduledTask(scheduleTriggerTask(task));
}
}
if (this.cronTasks != null) {
for (CronTask task : this.cronTasks) {
addScheduledTask(scheduleCronTask(task));
}
}
if (this.fixedRateTasks != null) {
for (IntervalTask task : this.fixedRateTasks) {
addScheduledTask(scheduleFixedRateTask(task));
}
}
if (this.fixedDelayTasks != null) {
for (IntervalTask task : this.fixedDelayTasks) {
addScheduledTask(scheduleFixedDelayTask(task));
}
}
}
private void addScheduledTask(ScheduledTask task) {
if (task != null) {
this.scheduledTasks.add(task);
}
}
/**
* Schedule the specified trigger task, either right away if possible
* or on initialization of the scheduler.
* @return a handle to the scheduled task, allowing to cancel it
* @since 4.3
*/
public ScheduledTask scheduleTriggerTask(TriggerTask task) {
ScheduledTask scheduledTask = this.unresolvedTasks.remove(task);
boolean newTask = false;
if (scheduledTask == null) {
scheduledTask = new ScheduledTask();
newTask = true;
}
if (this.taskScheduler != null) {
scheduledTask.future = this.taskScheduler.schedule(task.getRunnable(), task.getTrigger());
}
else {
addTriggerTask(task);
this.unresolvedTasks.put(task, scheduledTask);
}
return (newTask ? scheduledTask : null);
}
/**
* Schedule the specified cron task, either right away if possible
* or on initialization of the scheduler.
* @return a handle to the scheduled task, allowing to cancel it
* (or {@code null} if processing a previously registered task)
* @since 4.3
*/
public ScheduledTask scheduleCronTask(CronTask task) {
ScheduledTask scheduledTask = this.unresolvedTasks.remove(task);
boolean newTask = false;
if (scheduledTask == null) {
scheduledTask = new ScheduledTask();
newTask = true;
}
if (this.taskScheduler != null) {
scheduledTask.future = this.taskScheduler.schedule(task.getRunnable(), task.getTrigger());
}
else {
addCronTask(task);
this.unresolvedTasks.put(task, scheduledTask);
}
return (newTask ? scheduledTask : null);
}
/**
* Schedule the specified fixed-rate task, either right away if possible
* or on initialization of the scheduler.
* @return a handle to the scheduled task, allowing to cancel it
* (or {@code null} if processing a previously registered task)
* @since 4.3
*/
public ScheduledTask scheduleFixedRateTask(IntervalTask task) {
ScheduledTask scheduledTask = this.unresolvedTasks.remove(task);
boolean newTask = false;
if (scheduledTask == null) {
scheduledTask = new ScheduledTask();
newTask = true;
}
if (this.taskScheduler != null) {
if (task.getInitialDelay() > 0) {
Date startTime = new Date(System.currentTimeMillis() + task.getInitialDelay());
scheduledTask.future =
this.taskScheduler.scheduleAtFixedRate(task.getRunnable(), startTime, task.getInterval());
}
else {
scheduledTask.future =
this.taskScheduler.scheduleAtFixedRate(task.getRunnable(), task.getInterval());
}
}
else {
addFixedRateTask(task);
this.unresolvedTasks.put(task, scheduledTask);
}
return (newTask ? scheduledTask : null);
}
/**
* Schedule the specified fixed-delay task, either right away if possible
* or on initialization of the scheduler.
* @return a handle to the scheduled task, allowing to cancel it
* (or {@code null} if processing a previously registered task)
* @since 4.3
*/
public ScheduledTask scheduleFixedDelayTask(IntervalTask task) {
ScheduledTask scheduledTask = this.unresolvedTasks.remove(task);
boolean newTask = false;
if (scheduledTask == null) {
scheduledTask = new ScheduledTask();
newTask = true;
}
if (this.taskScheduler != null) {
if (task.getInitialDelay() > 0) {
Date startTime = new Date(System.currentTimeMillis() + task.getInitialDelay());
scheduledTask.future =
this.taskScheduler.scheduleWithFixedDelay(task.getRunnable(), startTime, task.getInterval());
}
else {
scheduledTask.future =
this.taskScheduler.scheduleWithFixedDelay(task.getRunnable(), task.getInterval());
}
}
else {
addFixedDelayTask(task);
this.unresolvedTasks.put(task, scheduledTask);
}
return (newTask ? scheduledTask : null);
}
@Override
public void destroy() {
for (ScheduledTask task : this.scheduledTasks) {
task.cancel();
}
if (this.localExecutor != null) {
this.localExecutor.shutdownNow();
}
}
}