/
QuartzScheduler.cs
2443 lines (2117 loc) · 83 KB
/
QuartzScheduler.cs
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#region License
/*
* All content copyright Marko Lahma, unless otherwise indicated. All rights reserved.
*
* 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.
*
*/
#endregion
using System.Globalization;
using System.Security;
using System.Text;
using Microsoft.Extensions.Logging;
using Quartz.Impl;
using Quartz.Impl.Matchers;
using Quartz.Impl.Triggers;
using Quartz.Logging;
using Quartz.Simpl;
using Quartz.Spi;
#if REMOTING
using System.Runtime.Remoting;
#endif // REMOTING
namespace Quartz.Core;
/// <summary>
/// This is the heart of Quartz, an indirect implementation of the <see cref="IScheduler" />
/// interface, containing methods to schedule <see cref="IJob" />s,
/// register <see cref="IJobListener" /> instances, etc.
/// </summary>
/// <seealso cref="IScheduler" />
/// <seealso cref="QuartzSchedulerThread" />
/// <seealso cref="IJobStore" />
/// <seealso cref="IThreadPool" />
/// <author>James House</author>
/// <author>Marko Lahma (.NET)</author>
public sealed class QuartzScheduler :
#if REMOTING
MarshalByRefObject,
#endif // REMOTING
IRemotableQuartzScheduler
{
private readonly ILogger<QuartzScheduler> logger;
private static readonly Version version;
internal readonly QuartzSchedulerResources resources = null!;
internal readonly QuartzSchedulerThread schedThread = null!;
private readonly List<ISchedulerListener> internalSchedulerListeners = new List<ISchedulerListener>(10);
private IJobFactory jobFactory = new PropertySettingJobFactory();
private readonly ExecutingJobsManager jobMgr;
private readonly QuartzRandom random = new QuartzRandom();
private readonly List<object> holdToPreventGc = new List<object>(5);
private volatile bool closed;
private volatile bool shuttingDown;
private DateTimeOffset? initialStart;
private bool boundRemotely;
/// <summary>
/// Initializes the <see cref="QuartzScheduler"/> class.
/// </summary>
static QuartzScheduler()
{
var asm = typeof(QuartzScheduler).Assembly;
version = asm.GetName().Version!;
}
/// <summary>
/// Gets the version of the Quartz Scheduler.
/// </summary>
/// <value>The version.</value>
public string Version => version.ToString();
/// <summary>
/// Gets the version major.
/// </summary>
/// <value>The version major.</value>
public static string VersionMajor => version.Major.ToString(CultureInfo.InvariantCulture);
/// <summary>
/// Gets the version minor.
/// </summary>
/// <value>The version minor.</value>
public static string VersionMinor => version.Minor.ToString(CultureInfo.InvariantCulture);
/// <summary>
/// Gets the version iteration.
/// </summary>
/// <value>The version iteration.</value>
public static string VersionIteration => version.Build.ToString(CultureInfo.InvariantCulture);
/// <summary>
/// Gets the scheduler signaler.
/// </summary>
/// <value>The scheduler signaler.</value>
public ISchedulerSignaler SchedulerSignaler { get; } = null!;
/// <summary>
/// Returns the name of the <see cref="QuartzScheduler" />.
/// </summary>
public string SchedulerName => resources.Name;
/// <summary>
/// Returns the instance Id of the <see cref="QuartzScheduler" />.
/// </summary>
public string SchedulerInstanceId => resources.InstanceId;
/// <summary>
/// Returns the <see cref="SchedulerContext" /> of the <see cref="IScheduler" />.
/// </summary>
public SchedulerContext SchedulerContext { get; } = new SchedulerContext();
/// <summary>
/// Gets or sets a value indicating whether to signal on scheduling change.
/// </summary>
/// <value>
/// <c>true</c> if scheduler should signal on scheduling change; otherwise, <c>false</c>.
/// </value>
public bool SignalOnSchedulingChange { get; set; } = true;
/// <summary>
/// Reports whether the <see cref="IScheduler" /> is paused.
/// </summary>
public bool InStandbyMode => schedThread.Paused;
/// <summary>
/// Gets the job store class.
/// </summary>
/// <value>The job store class.</value>
public Type JobStoreClass => resources.JobStore.GetType();
/// <summary>
/// Gets the thread pool class.
/// </summary>
/// <value>The thread pool class.</value>
public Type ThreadPoolClass => resources.ThreadPool.GetType();
/// <summary>
/// Gets the size of the thread pool.
/// </summary>
/// <value>The size of the thread pool.</value>
public int ThreadPoolSize => resources.ThreadPool.PoolSize;
/// <summary>
/// Reports whether the <see cref="IScheduler" /> has been Shutdown.
/// </summary>
public bool IsShutdown => closed;
public bool IsShuttingDown => shuttingDown;
public bool IsStarted => !shuttingDown && !closed && !InStandbyMode && initialStart != null;
/// <summary>
/// Return a list of <see cref="ICancellableJobExecutionContext" /> objects that
/// represent all currently executing Jobs in this Scheduler instance.
/// <para>
/// This method is not cluster aware. That is, it will only return Jobs
/// currently executing in this Scheduler instance, not across the entire
/// cluster.
/// </para>
/// <para>
/// Note that the list returned is an 'instantaneous' snap-shot, and that as
/// soon as it's returned, the true list of executing jobs may be different.
/// </para>
/// </summary>
public IReadOnlyCollection<IJobExecutionContext> CurrentlyExecutingJobs => jobMgr.ExecutingJobs;
/// <summary>
/// Register the given <see cref="ISchedulerListener" /> with the
/// <see cref="IScheduler" />'s list of internal listeners.
/// </summary>
/// <param name="schedulerListener"></param>
public void AddInternalSchedulerListener(ISchedulerListener schedulerListener)
{
lock (internalSchedulerListeners)
{
internalSchedulerListeners.Add(schedulerListener);
}
}
/// <summary>
/// Remove the given <see cref="ISchedulerListener" /> from the
/// <see cref="IScheduler" />'s list of internal listeners.
/// </summary>
/// <param name="schedulerListener"></param>
/// <returns>true if the identified listener was found in the list, andremoved.</returns>
public bool RemoveInternalSchedulerListener(ISchedulerListener schedulerListener)
{
lock (internalSchedulerListeners)
{
return internalSchedulerListeners.Remove(schedulerListener);
}
}
/// <summary>
/// Get a List containing all of the <i>internal</i> <see cref="ISchedulerListener" />s
/// registered with the <see cref="IScheduler" />.
/// </summary>
public IReadOnlyList<ISchedulerListener> InternalSchedulerListeners
{
get
{
lock (internalSchedulerListeners)
{
return new List<ISchedulerListener>(internalSchedulerListeners);
}
}
}
/// <summary>
/// Gets or sets the job factory.
/// </summary>
/// <value>The job factory.</value>
public IJobFactory JobFactory
{
get => jobFactory;
set
{
if (value == null)
{
ThrowHelper.ThrowArgumentException("JobFactory cannot be set to null!");
}
logger.LogInformation("JobFactory set to: {Value}", value);
jobFactory = value;
}
}
/// <summary>
/// Create a <see cref="QuartzScheduler" /> with the given configuration
/// properties.
/// </summary>
/// <seealso cref="QuartzSchedulerResources" />
public QuartzScheduler(QuartzSchedulerResources resources)
{
this.resources = resources;
logger = LogProvider.CreateLogger<QuartzScheduler>();
schedThread = new QuartzSchedulerThread(this, resources);
schedThread.Start();
jobMgr = new ExecutingJobsManager();
var errLogger = new ErrorLogger();
AddInternalSchedulerListener(errLogger);
SchedulerSignaler = new SchedulerSignalerImpl(this, schedThread);
logger.LogInformation("Quartz Scheduler created");
}
public void Initialize()
{
try
{
Bind();
}
catch (Exception re)
{
ThrowHelper.ThrowSchedulerException("Unable to bind scheduler to remoting.", re);
}
}
/// <summary>
/// Bind the scheduler to remoting infrastructure.
/// </summary>
private void Bind()
{
if (resources.SchedulerExporter != null)
{
resources.SchedulerExporter.Bind(this);
boundRemotely = true;
}
}
/// <summary>
/// Un-bind the scheduler from remoting infrastructure.
/// </summary>
private void UnBind()
{
resources.SchedulerExporter?.UnBind(this);
}
/// <summary>
/// Adds an object that should be kept as reference to prevent
/// it from being garbage collected.
/// </summary>
/// <param name="obj">The obj.</param>
public void AddNoGCObject(object obj)
{
holdToPreventGc.Add(obj);
}
/// <summary>
/// Removes the object from garbage collection protected list.
/// </summary>
/// <param name="obj">The obj.</param>
/// <returns></returns>
public bool RemoveNoGCObject(object obj)
{
return holdToPreventGc.Remove(obj);
}
/// <summary>
/// Starts the <see cref="QuartzScheduler" />'s threads that fire <see cref="ITrigger" />s.
/// <para>
/// All <see cref="ITrigger" />s that have misfired will
/// be passed to the appropriate TriggerListener(s).
/// </para>
/// </summary>
public async ValueTask Start(CancellationToken cancellationToken = default)
{
if (shuttingDown || closed)
{
ThrowHelper.ThrowSchedulerException("The Scheduler cannot be restarted after Shutdown() has been called.");
}
await NotifySchedulerListenersStarting(cancellationToken).ConfigureAwait(false);
if (!initialStart.HasValue)
{
initialStart = this.resources.TimeProvider.GetUtcNow();
await resources.JobStore.SchedulerStarted(cancellationToken).ConfigureAwait(false);
await StartPlugins(cancellationToken).ConfigureAwait(false);
}
else
{
await resources.JobStore.SchedulerResumed(cancellationToken).ConfigureAwait(false);
}
schedThread.TogglePause(false);
logger.LogInformation("Scheduler {SchedulerIdentifier} started.", resources.GetUniqueIdentifier());
await NotifySchedulerListenersStarted(cancellationToken).ConfigureAwait(false);
}
public ValueTask StartDelayed(
TimeSpan delay,
CancellationToken cancellationToken = default)
{
if (shuttingDown || closed)
{
ThrowHelper.ThrowSchedulerException(
"The Scheduler cannot be restarted after Shutdown() has been called.");
}
#pragma warning disable MA0134
Task.Run(async () =>
{
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
try
{
await Start(cancellationToken).ConfigureAwait(false);
}
catch (SchedulerException se)
{
logger.LogError(se, "Unable to start scheduler after startup delay.");
}
}, cancellationToken);
#pragma warning restore MA0134
return default;
}
/// <summary>
/// Temporarily halts the <see cref="QuartzScheduler" />'s firing of <see cref="ITrigger" />s.
/// <para>
/// The scheduler is not destroyed, and can be re-started at any time.
/// </para>
/// </summary>
public async ValueTask Standby(CancellationToken cancellationToken = default)
{
await resources.JobStore.SchedulerPaused(cancellationToken).ConfigureAwait(false);
schedThread.TogglePause(true);
logger.LogInformation("Scheduler {SchedulerIdentifier} paused.", resources.GetUniqueIdentifier());
await NotifySchedulerListenersInStandbyMode(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the running since.
/// </summary>
/// <value>The running since.</value>
public DateTimeOffset? RunningSince => initialStart;
/// <summary>
/// Gets the number of jobs executed.
/// </summary>
/// <value>The number of jobs executed.</value>
public int NumJobsExecuted => jobMgr.NumJobsFired;
/// <summary>
/// Gets a value indicating whether this scheduler supports persistence.
/// </summary>
/// <value><c>true</c> if supports persistence; otherwise, <c>false</c>.</value>
public bool SupportsPersistence => resources.JobStore.SupportsPersistence;
public bool Clustered => resources.JobStore.Clustered;
/// <summary>
/// Halts the <see cref="QuartzScheduler" />'s firing of <see cref="ITrigger" />s,
/// and cleans up all resources associated with the QuartzScheduler.
/// Equivalent to <see cref="Shutdown(bool, CancellationToken)" />.
/// <para>
/// The scheduler cannot be re-started.
/// </para>
/// </summary>
public ValueTask Shutdown(CancellationToken cancellationToken = default)
{
return Shutdown(false, cancellationToken);
}
/// <summary>
/// Halts the <see cref="QuartzScheduler" />'s firing of <see cref="ITrigger" />s,
/// and cleans up all resources associated with the QuartzScheduler.
/// <para>
/// The scheduler cannot be re-started.
/// </para>
/// </summary>
/// <param name="waitForJobsToComplete">
/// if <see langword="true" /> the scheduler will not allow this method
/// to return until all currently executing jobs have completed.
/// </param>
/// <param name="cancellationToken">The cancellation instruction.</param>
public async ValueTask Shutdown(
bool waitForJobsToComplete,
CancellationToken cancellationToken = default)
{
if (shuttingDown || closed)
{
return;
}
shuttingDown = true;
logger.LogInformation("Scheduler {SchedulerIdentifier} shutting down.", resources.GetUniqueIdentifier());
await Standby(cancellationToken).ConfigureAwait(false);
await schedThread.Halt(waitForJobsToComplete).ConfigureAwait(false);
await NotifySchedulerListenersShuttingdown(cancellationToken).ConfigureAwait(false);
if (resources.InterruptJobsOnShutdown && !waitForJobsToComplete
|| resources.InterruptJobsOnShutdownWithWait && waitForJobsToComplete)
{
var jobs = CurrentlyExecutingJobs.OfType<ICancellableJobExecutionContext>();
foreach (var job in jobs)
{
job.Cancel();
}
}
resources.ThreadPool.Shutdown(waitForJobsToComplete);
// Scheduler thread may have be waiting for the fire time of an acquired
// trigger and need time to release the trigger once halted, so make sure
// the thread is dead before continuing to shutdown the job store.
await schedThread.Shutdown().ConfigureAwait(false);
closed = true;
if (boundRemotely)
{
try
{
UnBind();
}
#if REMOTING
catch (RemotingException)
#else // REMOTING
catch (Exception) // TODO (NetCore Port): Determine the correct exception type
#endif // REMOTING
{
}
}
await ShutdownPlugins(cancellationToken).ConfigureAwait(false);
await resources.JobStore.Shutdown(cancellationToken).ConfigureAwait(false);
await NotifySchedulerListenersShutdown(cancellationToken).ConfigureAwait(false);
SchedulerRepository.Instance.Remove(resources.Name);
holdToPreventGc.Clear();
logger.LogInformation("Scheduler {SchedulerIdentifier} Shutdown complete.", resources.GetUniqueIdentifier());
}
/// <summary>
/// Validates the state.
/// </summary>
public void ValidateState()
{
if (IsShutdown)
{
ThrowHelper.ThrowSchedulerException("The Scheduler has been Shutdown.");
}
// other conditions to check (?)
}
/// <summary>
/// Add the <see cref="IJob" /> identified by the given
/// <see cref="IJobDetail" /> to the Scheduler, and
/// associate the given <see cref="ITrigger" /> with it.
/// <para>
/// If the given Trigger does not reference any <see cref="IJob" />, then it
/// will be set to reference the Job passed with it into this method.
/// </para>
/// </summary>
public async ValueTask<DateTimeOffset> ScheduleJob(
IJobDetail jobDetail,
ITrigger trigger,
CancellationToken cancellationToken = default)
{
ValidateState();
if (jobDetail == null)
{
ThrowHelper.ThrowSchedulerException("JobDetail cannot be null");
}
if (trigger == null)
{
ThrowHelper.ThrowSchedulerException("Trigger cannot be null");
}
if (jobDetail.Key == null)
{
ThrowHelper.ThrowSchedulerException("Job's key cannot be null");
}
if (jobDetail.JobType == null)
{
ThrowHelper.ThrowSchedulerException("Job's class cannot be null");
}
IOperableTrigger trig = (IOperableTrigger) trigger;
if (trigger.JobKey == null)
{
trig.JobKey = jobDetail.Key;
}
else if (!trigger.JobKey.Equals(jobDetail.Key))
{
ThrowHelper.ThrowSchedulerException("Trigger does not reference given job!");
}
trig.Validate();
ICalendar? cal = null;
if (trigger.CalendarName != null)
{
cal = await resources.JobStore.RetrieveCalendar(trigger.CalendarName, cancellationToken).ConfigureAwait(false);
if (cal == null)
{
ThrowHelper.ThrowSchedulerException($"Calendar not found: {trigger.CalendarName}");
}
}
DateTimeOffset? ft = trig.ComputeFirstFireTimeUtc(cal);
if (!ft.HasValue)
{
var message = $"Based on configured schedule, the given trigger '{trigger.Key}' will never fire.";
ThrowHelper.ThrowSchedulerException(message);
}
await resources.JobStore.StoreJobAndTrigger(jobDetail, trig, cancellationToken).ConfigureAwait(false);
await NotifySchedulerListenersJobAdded(jobDetail, cancellationToken).ConfigureAwait(false);
NotifySchedulerThread(trigger.GetNextFireTimeUtc());
await NotifySchedulerListenersScheduled(trigger, cancellationToken).ConfigureAwait(false);
return ft.Value;
}
/// <summary>
/// Schedule the given <see cref="ITrigger" /> with the
/// <see cref="IJob" /> identified by the <see cref="ITrigger" />'s settings.
/// </summary>
public async ValueTask<DateTimeOffset> ScheduleJob(
ITrigger trigger,
CancellationToken cancellationToken = default)
{
ValidateState();
if (trigger == null)
{
ThrowHelper.ThrowSchedulerException("Trigger cannot be null");
}
IOperableTrigger trig = (IOperableTrigger) trigger;
trig.Validate();
ICalendar? cal = null;
if (trigger.CalendarName != null)
{
cal = await resources.JobStore.RetrieveCalendar(trigger.CalendarName, cancellationToken).ConfigureAwait(false);
if (cal == null)
{
ThrowHelper.ThrowSchedulerException($"Calendar not found: {trigger.CalendarName}");
}
}
DateTimeOffset? ft = trig.ComputeFirstFireTimeUtc(cal);
if (!ft.HasValue)
{
var message = $"Based on configured schedule, the given trigger '{trigger.Key}' will never fire.";
ThrowHelper.ThrowSchedulerException(message);
}
await resources.JobStore.StoreTrigger(trig, false, cancellationToken).ConfigureAwait(false);
NotifySchedulerThread(trigger.GetNextFireTimeUtc());
await NotifySchedulerListenersScheduled(trigger, cancellationToken).ConfigureAwait(false);
return ft.Value;
}
/// <summary>
/// Add the given <see cref="IJob" /> to the Scheduler - with no associated
/// <see cref="ITrigger" />. The <see cref="IJob" /> will be 'dormant' until
/// it is scheduled with a <see cref="ITrigger" />, or <see cref="IScheduler.TriggerJob(Quartz.JobKey, CancellationToken)" />
/// is called for it.
/// <para>
/// The <see cref="IJob" /> must by definition be 'durable', if it is not,
/// SchedulerException will be thrown.
/// </para>
/// </summary>
public ValueTask AddJob(
IJobDetail jobDetail,
bool replace,
CancellationToken cancellationToken = default)
{
return AddJob(jobDetail, replace, false, cancellationToken);
}
public async ValueTask AddJob(
IJobDetail jobDetail,
bool replace,
bool storeNonDurableWhileAwaitingScheduling,
CancellationToken cancellationToken = default)
{
ValidateState();
if (!storeNonDurableWhileAwaitingScheduling && !jobDetail.Durable)
{
ThrowHelper.ThrowSchedulerException("Jobs added with no trigger must be durable.");
}
await resources.JobStore.StoreJob(jobDetail, replace, cancellationToken).ConfigureAwait(false);
NotifySchedulerThread(null);
await NotifySchedulerListenersJobAdded(jobDetail, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Delete the identified <see cref="IJob" /> from the Scheduler - and any
/// associated <see cref="ITrigger" />s.
/// </summary>
/// <returns> true if the Job was found and deleted.</returns>
public async ValueTask<bool> DeleteJob(
JobKey jobKey,
CancellationToken cancellationToken = default)
{
ValidateState();
bool result = false;
var triggers = await GetTriggersOfJob(jobKey, cancellationToken).ConfigureAwait(false);
foreach (ITrigger trigger in triggers)
{
if (!await UnscheduleJob(trigger.Key, cancellationToken).ConfigureAwait(false))
{
StringBuilder sb = new StringBuilder()
.Append("Unable to unschedule trigger [")
.Append(trigger.Key).Append("] while deleting job [")
.Append(jobKey).Append("]");
ThrowHelper.ThrowSchedulerException(sb.ToString());
}
result = true;
}
result = await resources.JobStore.RemoveJob(jobKey, cancellationToken).ConfigureAwait(false) || result;
if (result)
{
NotifySchedulerThread(null);
await NotifySchedulerListenersJobDeleted(jobKey, cancellationToken).ConfigureAwait(false);
}
return result;
}
public async ValueTask<bool> DeleteJobs(
IReadOnlyCollection<JobKey> jobKeys,
CancellationToken cancellationToken = default)
{
ValidateState();
bool result = await resources.JobStore.RemoveJobs(jobKeys, cancellationToken).ConfigureAwait(false);
NotifySchedulerThread(null);
foreach (JobKey key in jobKeys)
{
await NotifySchedulerListenersJobDeleted(key, cancellationToken).ConfigureAwait(false);
}
return result;
}
public async ValueTask ScheduleJobs(
IReadOnlyDictionary<IJobDetail, IReadOnlyCollection<ITrigger>> triggersAndJobs,
bool replace,
CancellationToken cancellationToken = default)
{
ValidateState();
// make sure all triggers refer to their associated job
foreach (var pair in triggersAndJobs)
{
var job = pair.Key;
var triggers = pair.Value;
if (job == null) // there can be one of these (for adding a bulk set of triggers for pre-existing jobs)
{
continue;
}
if (triggers == null) // this is possible because the job may be durable, and not yet be having triggers
{
continue;
}
foreach (var t in triggers)
{
var trigger = (IOperableTrigger) t;
trigger.JobKey = job.Key;
trigger.Validate();
ICalendar? cal = null;
if (trigger.CalendarName != null)
{
cal = await resources.JobStore.RetrieveCalendar(trigger.CalendarName, cancellationToken).ConfigureAwait(false);
if (cal == null)
{
var message = $"Calendar '{trigger.CalendarName}' not found for trigger: {trigger.Key}";
ThrowHelper.ThrowSchedulerException(message);
}
}
DateTimeOffset? ft = trigger.ComputeFirstFireTimeUtc(cal);
if (ft == null)
{
var message = $"Based on configured schedule, the given trigger '{trigger.Key}' will never fire.";
ThrowHelper.ThrowSchedulerException(message);
}
}
}
await resources.JobStore.StoreJobsAndTriggers(triggersAndJobs, replace, cancellationToken).ConfigureAwait(false);
NotifySchedulerThread(null);
foreach (var pair in triggersAndJobs)
{
var job = pair.Key;
var triggers = pair.Value;
await NotifySchedulerListenersJobAdded(job, cancellationToken).ConfigureAwait(false);
foreach (var trigger in triggers)
{
await NotifySchedulerListenersScheduled(trigger, cancellationToken).ConfigureAwait(false);
}
}
}
public ValueTask ScheduleJob(
IJobDetail jobDetail,
IReadOnlyCollection<ITrigger> triggersForJob,
bool replace,
CancellationToken cancellationToken = default)
{
var triggersAndJobs = new Dictionary<IJobDetail, IReadOnlyCollection<ITrigger>>();
triggersAndJobs.Add(jobDetail, triggersForJob);
return ScheduleJobs(triggersAndJobs, replace, cancellationToken);
}
public async ValueTask<bool> UnscheduleJobs(
IReadOnlyCollection<TriggerKey> triggerKeys,
CancellationToken cancellationToken = default)
{
ValidateState();
bool result = await resources.JobStore.RemoveTriggers(triggerKeys, cancellationToken).ConfigureAwait(false);
NotifySchedulerThread(null);
await Task.WhenAll(triggerKeys.Select(x => NotifySchedulerListenersUnscheduled(x, cancellationToken))).ConfigureAwait(false);
return result;
}
/// <summary>
/// Remove the indicated <see cref="ITrigger" /> from the
/// scheduler.
/// </summary>
public async ValueTask<bool> UnscheduleJob(
TriggerKey triggerKey,
CancellationToken cancellationToken = default)
{
ValidateState();
if (await resources.JobStore.RemoveTrigger(triggerKey, cancellationToken).ConfigureAwait(false))
{
NotifySchedulerThread(null);
await NotifySchedulerListenersUnscheduled(triggerKey, cancellationToken).ConfigureAwait(false);
}
else
{
return false;
}
return true;
}
/// <summary>
/// Remove (delete) the <see cref="ITrigger" /> with the
/// given name, and store the new given one - which must be associated
/// with the same job.
/// </summary>
/// <param name="triggerKey">the key of the trigger</param>
/// <param name="newTrigger">The new <see cref="ITrigger" /> to be stored.</param>
/// <param name="cancellationToken">The cancellation instruction.</param>
/// <returns>
/// <see langword="null" /> if a <see cref="ITrigger" /> with the given
/// name and group was not found and removed from the store, otherwise
/// the first fire time of the newly scheduled trigger.
/// </returns>
public async ValueTask<DateTimeOffset?> RescheduleJob(
TriggerKey triggerKey,
ITrigger newTrigger,
CancellationToken cancellationToken = default)
{
ValidateState();
if (triggerKey == null)
{
ThrowHelper.ThrowArgumentException("triggerKey cannot be null");
}
if (newTrigger == null)
{
ThrowHelper.ThrowArgumentException("newTrigger cannot be null");
}
var trigger = (IOperableTrigger) newTrigger;
ITrigger? oldTrigger = await GetTrigger(triggerKey, cancellationToken).ConfigureAwait(false);
if (oldTrigger == null)
{
return null;
}
trigger.JobKey = oldTrigger.JobKey;
trigger.Validate();
ICalendar? cal = null;
if (newTrigger.CalendarName != null)
{
cal = await resources.JobStore.RetrieveCalendar(newTrigger.CalendarName, cancellationToken).ConfigureAwait(false);
}
DateTimeOffset? ft;
if (trigger.GetNextFireTimeUtc() != null)
{
// use a cloned trigger so that we don't lose possible forcefully set next fire time
var clonedTrigger = (IOperableTrigger) trigger.Clone();
ft = clonedTrigger.ComputeFirstFireTimeUtc(cal);
}
else
{
ft = trigger.ComputeFirstFireTimeUtc(cal);
}
if (!ft.HasValue)
{
var message = $"Based on configured schedule, the given trigger '{trigger.Key}' will never fire.";
ThrowHelper.ThrowSchedulerException(message);
}
if (await resources.JobStore.ReplaceTrigger(triggerKey, trigger, cancellationToken).ConfigureAwait(false))
{
NotifySchedulerThread(newTrigger.GetNextFireTimeUtc());
await NotifySchedulerListenersUnscheduled(triggerKey, cancellationToken).ConfigureAwait(false);
await NotifySchedulerListenersScheduled(newTrigger, cancellationToken).ConfigureAwait(false);
}
else
{
return null;
}
return ft;
}
private string NewTriggerId()
{
long r = NextLong(random);
if (r < 0)
{
r = -r;
}
return "MT_" + Convert.ToString(r, CultureInfo.InvariantCulture);
}
/// <summary>
/// Creates a new positive random number
/// </summary>
/// <param name="random">The last random obtained</param>
/// <returns>Returns a new positive random number</returns>
private static long NextLong(QuartzRandom random)
{
long temporaryLong = random.Next();
temporaryLong = (temporaryLong << 32) + random.Next();
if (random.Next(-1, 1) < 0)
{
return -temporaryLong;
}
return temporaryLong;
}
/// <summary>
/// Trigger the identified <see cref="IJob" /> (Execute it now) - with a non-volatile trigger.
/// </summary>
public async ValueTask TriggerJob(
JobKey jobKey,
JobDataMap? data,
CancellationToken cancellationToken = default)
{
ValidateState();
// TODO: use builder
IOperableTrigger trig = new SimpleTriggerImpl(
NewTriggerId(),
SchedulerConstants.DefaultGroup,
jobKey.Name,
jobKey.Group,
this.resources.TimeProvider.GetUtcNow(),
null,
0,
TimeSpan.Zero);
trig.ComputeFirstFireTimeUtc(null);
if (data != null)
{
trig.JobDataMap = data;
}
bool collision = true;
while (collision)
{
try
{
await resources.JobStore.StoreTrigger(trig, false, cancellationToken).ConfigureAwait(false);
collision = false;
}
catch (ObjectAlreadyExistsException)
{
trig.Key = new TriggerKey(NewTriggerId(), SchedulerConstants.DefaultGroup);
}
}
NotifySchedulerThread(trig.GetNextFireTimeUtc());
await NotifySchedulerListenersScheduled(trig, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Store and schedule the identified <see cref="IOperableTrigger"/>
/// </summary>
public async Task TriggerJob(
IOperableTrigger trig,
CancellationToken cancellationToken = default)
{
ValidateState();
trig.ComputeFirstFireTimeUtc(null);
bool collision = true;
while (collision)
{
try
{
await resources.JobStore.StoreTrigger(trig, false, cancellationToken).ConfigureAwait(false);
collision = false;