-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
RAMJobStore.cs
2022 lines (1830 loc) · 70.5 KB
/
RAMJobStore.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.Collections.Concurrent;
using System.Globalization;
using System.Text;
using Microsoft.Extensions.Logging;
using Quartz.Impl.Matchers;
using Quartz.Logging;
using Quartz.Spi;
namespace Quartz.Simpl;
/// <summary>
/// This class implements a <see cref="IJobStore" /> that
/// utilizes RAM as its storage device.
/// <para>
/// As you should know, the ramification of this is that access is extremely
/// fast, but the data is completely volatile - therefore this <see cref="IJobStore" />
/// should not be used if true persistence between program shutdowns is
/// required.
/// </para>
/// </summary>
/// <author>James House</author>
/// <author>Sharada Jambula</author>
/// <author>Marko Lahma (.NET)</author>
public class RAMJobStore : IJobStore
{
private readonly object lockObject = new object();
private readonly Dictionary<JobKey, JobWrapper> jobsByKey = new Dictionary<JobKey, JobWrapper>();
private readonly ConcurrentDictionary<TriggerKey, TriggerWrapper> triggersByKey = new ConcurrentDictionary<TriggerKey, TriggerWrapper>();
private readonly Dictionary<string, Dictionary<JobKey, JobWrapper>> jobsByGroup = new Dictionary<string, Dictionary<JobKey, JobWrapper>>();
private readonly Dictionary<string, Dictionary<TriggerKey, TriggerWrapper>> triggersByGroup = new Dictionary<string, Dictionary<TriggerKey, TriggerWrapper>>();
private readonly SortedSet<TriggerWrapper> timeTriggers = new SortedSet<TriggerWrapper>(new TriggerWrapperComparator());
private readonly Dictionary<string, ICalendar> calendarsByName = new Dictionary<string, ICalendar>();
private readonly Dictionary<JobKey, List<TriggerWrapper>> triggersByJob = new Dictionary<JobKey, List<TriggerWrapper>>();
private readonly HashSet<string> pausedTriggerGroups = new HashSet<string>();
private readonly HashSet<string> pausedJobGroups = new HashSet<string>();
private readonly HashSet<JobKey> blockedJobs = new HashSet<JobKey>();
private TimeSpan misfireThreshold = TimeSpan.FromSeconds(5);
private ISchedulerSignaler signaler = null!;
private TimeProvider timeProvider = TimeProvider.System;
/// <summary>
/// Initializes a new instance of the <see cref="RAMJobStore"/> class.
/// </summary>
public RAMJobStore()
{
logger = LogProvider.CreateLogger<RAMJobStore>();
}
/// <summary>
/// Gets or sets the time by which a trigger must have missed its next-fire-time, in order for it to
/// be considered "misfired" and thus have its misfire instruction applied.
/// </summary>
/// <value>
/// The time by which a trigger must have missed its next-fire-time, in order for it to be considered
/// "misfired" and thus have its misfire instruction applied. The default is <c>5</c> seconds.
/// </value>
/// <exception cref="ArgumentException"><paramref name="value"/> represents less than one millisecond.</exception>
[TimeSpanParseRule(TimeSpanParseRule.Milliseconds)]
public virtual TimeSpan MisfireThreshold
{
get => misfireThreshold;
set
{
if (value.TotalMilliseconds < 1)
{
ThrowHelper.ThrowArgumentException("MisfireThreshold must be larger than 0");
}
misfireThreshold = value;
}
}
private static long ftrCtr = TimeProvider.System.GetTimestamp();
/// <summary>
/// Gets the fired trigger record id.
/// </summary>
/// <returns>The fired trigger record id.</returns>
protected virtual string GetFiredTriggerRecordId()
{
long value = Interlocked.Increment(ref ftrCtr);
return value.ToString(CultureInfo.InvariantCulture);
}
/// <summary>
/// Called by the QuartzScheduler before the <see cref="IJobStore" /> is
/// used, in order to give the it a chance to Initialize.
/// </summary>
public virtual ValueTask Initialize(
ITypeLoadHelper loadHelper,
ISchedulerSignaler signaler,
CancellationToken cancellationToken = default)
{
this.signaler = signaler;
logger.LogInformation("RAMJobStore initialized.");
return default;
}
/// <summary>
/// Called by the QuartzScheduler to inform the <see cref="IJobStore" /> that
/// the scheduler has started.
/// </summary>
public virtual ValueTask SchedulerStarted(CancellationToken cancellationToken = default)
{
// nothing to do
return default(ValueTask);
}
/// <summary>
/// Called by the QuartzScheduler to inform the JobStore that
/// the scheduler has been paused.
/// </summary>
public ValueTask SchedulerPaused(CancellationToken cancellationToken = default)
{
// nothing to do
return default;
}
/// <summary>
/// Called by the QuartzScheduler to inform the JobStore that
/// the scheduler has resumed after being paused.
/// </summary>
public ValueTask SchedulerResumed(CancellationToken cancellationToken = default)
{
// nothing to do
return default;
}
/// <summary>
/// Called by the QuartzScheduler to inform the <see cref="IJobStore" /> that
/// it should free up all of it's resources because the scheduler is
/// shutting down.
/// </summary>
public virtual ValueTask Shutdown(CancellationToken cancellationToken = default)
{
return default;
}
/// <summary>
/// Returns whether this instance supports persistence.
/// </summary>
/// <value></value>
/// <returns></returns>
public virtual bool SupportsPersistence => false;
/// <summary>
/// Clears (deletes!) all scheduling data - all <see cref="IJob"/>s, <see cref="ITrigger" />s
/// <see cref="ICalendar"/>s.
/// </summary>
public ValueTask<object> ClearAllSchedulingData(CancellationToken cancellationToken = default)
{
lock (lockObject)
{
// unschedule jobs (delete triggers)
foreach (string group in new List<string>(triggersByGroup.Keys))
{
var keys = GetTriggerKeysInternal(GroupMatcher<TriggerKey>.GroupEquals(group));
foreach (TriggerKey key in keys)
{
RemoveTriggerInternal(key);
}
}
// delete jobs
foreach (string group in new List<string>(jobsByGroup.Keys))
{
var keys = GetJobKeysInternal(GroupMatcher<JobKey>.GroupEquals(group));
foreach (JobKey key in keys)
{
RemoveJobInternal(key);
}
}
// delete calendars
foreach (string name in new List<string>(calendarsByName.Keys))
{
RemoveCalendarInternal(name);
}
}
return default;
}
private ILogger<RAMJobStore> logger { get; }
/// <summary>
/// Store the given <see cref="IJobDetail" /> and <see cref="ITrigger" />.
/// </summary>
/// <param name="newJob">The <see cref="IJobDetail" /> to be stored.</param>
/// <param name="newTrigger">The <see cref="ITrigger" /> to be stored.</param>
/// <param name="cancellationToken">The cancellation instruction.</param>
public virtual ValueTask StoreJobAndTrigger(
IJobDetail newJob,
IOperableTrigger newTrigger,
CancellationToken cancellationToken = default)
{
StoreJobInternal(newJob, false);
StoreTriggerInternal(newTrigger, false);
return default;
}
/// <summary>
/// Returns true if the given job group is paused.
/// </summary>
/// <param name="groupName">Job group name</param>
/// <param name="cancellationToken">The cancellation instruction.</param>
/// <returns></returns>
public virtual ValueTask<bool> IsJobGroupPaused(
string groupName,
CancellationToken cancellationToken = default)
{
return new ValueTask<bool>(pausedJobGroups.Contains(groupName));
}
/// <summary>
/// Returns true if the given TriggerGroup is paused.
/// </summary>
/// <returns></returns>
public virtual ValueTask<bool> IsTriggerGroupPaused(
string groupName,
CancellationToken cancellationToken = default)
{
return new ValueTask<bool>(pausedTriggerGroups.Contains(groupName));
}
/// <summary>
/// Store the given <see cref="IJob" />.
/// </summary>
/// <param name="newJob">The <see cref="IJob" /> to be stored.</param>
/// <param name="replaceExisting">If <see langword="true" />, any <see cref="IJob" /> existing in the
/// <see cref="IJobStore" /> with the same name and group should be
/// over-written.</param>
/// <param name="cancellationToken">The cancellation instruction.</param>
public virtual ValueTask<object> StoreJob(
IJobDetail newJob,
bool replaceExisting,
CancellationToken cancellationToken = default)
{
StoreJobInternal(newJob, replaceExisting);
return default;
}
private void StoreJobInternal(IJobDetail newJob, bool replaceExisting)
{
lock (lockObject)
{
var jobKey = newJob.Key;
if (jobsByKey.TryGetValue(jobKey, out var originalJob))
{
if (!replaceExisting)
{
ThrowHelper.ThrowObjectAlreadyExistsException(newJob);
}
// update job detail
originalJob.JobDetail = newJob.Clone();
}
else
{
// get job group
if (!jobsByGroup.TryGetValue(jobKey.Group, out var grpMap))
{
grpMap = new Dictionary<JobKey, JobWrapper>();
jobsByGroup[jobKey.Group] = grpMap;
}
JobWrapper jw = new JobWrapper(newJob.Clone());
// add to jobs by group
grpMap[jobKey] = jw;
// add to jobs by FQN map
jobsByKey[jobKey] = jw;
}
}
}
/// <summary>
/// Remove (delete) the <see cref="IJob" /> with the given
/// name, and any <see cref="ITrigger" /> s that reference
/// it.
/// </summary>
/// <returns>
/// <see langword="true" /> if a <see cref="IJob" /> with the given name and
/// group was found and removed from the store.
/// </returns>
public virtual ValueTask<bool> RemoveJob(
JobKey jobKey,
CancellationToken cancellationToken = default)
{
return new ValueTask<bool>(RemoveJobInternal(jobKey));
}
private bool RemoveJobInternal(JobKey jobKey)
{
lock (lockObject)
{
bool found = false;
var triggersForJob = GetTriggersForJobInternal(jobKey);
foreach (IOperableTrigger trigger in triggersForJob)
{
RemoveTriggerInternal(trigger.Key);
found = true;
}
found = jobsByKey.Remove(jobKey) || found;
if (found)
{
if (jobsByGroup.TryGetValue(jobKey.Group, out var grpMap))
{
if (grpMap.Remove(jobKey) && grpMap.Count == 0)
{
jobsByGroup.Remove(jobKey.Group);
}
}
}
return found;
}
}
public ValueTask<bool> RemoveJobs(
IReadOnlyCollection<JobKey> jobKeys,
CancellationToken cancellationToken = default)
{
lock (lockObject)
{
bool allFound = true;
foreach (JobKey key in jobKeys)
{
allFound = RemoveJobInternal(key) && allFound;
}
return new ValueTask<bool>(allFound);
}
}
public ValueTask<bool> RemoveTriggers(
IReadOnlyCollection<TriggerKey> triggerKeys,
CancellationToken cancellationToken = default)
{
lock (lockObject)
{
bool allFound = true;
foreach (TriggerKey key in triggerKeys)
{
allFound = RemoveTriggerInternal(key) && allFound;
}
return new ValueTask<bool>(allFound);
}
}
public ValueTask<object> StoreJobsAndTriggers(
IReadOnlyDictionary<IJobDetail, IReadOnlyCollection<ITrigger>> triggersAndJobs,
bool replace,
CancellationToken cancellationToken = default)
{
lock (lockObject)
{
// make sure there are no collisions...
if (!replace)
{
foreach (var triggersByJob in triggersAndJobs)
{
var job = triggersByJob.Key;
if (jobsByKey.ContainsKey(job.Key))
{
ThrowHelper.ThrowObjectAlreadyExistsException(job);
}
foreach (ITrigger trigger in triggersByJob.Value)
{
if (triggersByKey.ContainsKey(trigger.Key))
{
ThrowHelper.ThrowObjectAlreadyExistsException(trigger);
}
}
}
}
// do bulk add...
foreach (var triggersByJob in triggersAndJobs)
{
StoreJobInternal(triggersByJob.Key, true);
foreach (ITrigger trigger in triggersByJob.Value)
{
StoreTriggerInternal((IOperableTrigger) trigger, true);
}
}
}
return default;
}
/// <summary>
/// Remove (delete) the <see cref="ITrigger" /> with the
/// given name.
/// </summary>
/// <returns>
/// <see langword="true" /> if a <see cref="ITrigger" /> with the given
/// name and group was found and removed from the store.
/// </returns>
public virtual ValueTask<bool> RemoveTrigger(
TriggerKey triggerKey,
CancellationToken cancellationToken = default)
{
return RemoveTrigger(triggerKey, true);
}
/// <summary>
/// Store the given <see cref="ITrigger" />.
/// </summary>
/// <param name="newTrigger">The <see cref="ITrigger" /> to be stored.</param>
/// <param name="replaceExisting">If <see langword="true" />, any <see cref="ITrigger" /> existing in
/// the <see cref="IJobStore" /> with the same name and group should
/// be over-written.</param>
/// <param name="cancellationToken">The cancellation instruction.</param>
public virtual ValueTask<object> StoreTrigger(
IOperableTrigger newTrigger,
bool replaceExisting,
CancellationToken cancellationToken = default)
{
StoreTriggerInternal(newTrigger, replaceExisting);
return default;
}
private void StoreTriggerInternal(
IOperableTrigger newTrigger,
bool replaceExisting)
{
lock (lockObject)
{
TriggerWrapper tw = new TriggerWrapper((IOperableTrigger) newTrigger.Clone());
if (triggersByKey.ContainsKey(tw.TriggerKey))
{
if (!replaceExisting)
{
ThrowHelper.ThrowObjectAlreadyExistsException(newTrigger);
}
// don't delete orphaned job, this trigger has the job anyways
RemoveTriggerInternal(tw.TriggerKey, removeOrphanedJob: false);
}
if (!CheckExistsInternal(tw.JobKey))
{
ThrowHelper.ThrowJobPersistenceException("The job (" + tw.JobKey +
") referenced by the trigger does not exist.");
}
// add to triggers by job
if (!triggersByJob.TryGetValue(tw.JobKey, out var jobList))
{
jobList = new List<TriggerWrapper>(1);
triggersByJob.Add(tw.JobKey, jobList);
}
jobList.Add(tw);
// add to triggers by group
if (!triggersByGroup.TryGetValue(tw.TriggerKey.Group, out var grpMap))
{
grpMap = new Dictionary<TriggerKey, TriggerWrapper>();
triggersByGroup[tw.TriggerKey.Group] = grpMap;
}
grpMap[tw.TriggerKey] = tw;
// add to triggers by FQN map
triggersByKey[tw.TriggerKey] = tw;
if (pausedTriggerGroups.Contains(tw.TriggerKey.Group) || pausedJobGroups.Contains(tw.JobKey.Group))
{
tw.state = InternalTriggerState.Paused;
if (blockedJobs.Contains(tw.JobKey))
{
tw.state = InternalTriggerState.PausedAndBlocked;
}
}
else if (blockedJobs.Contains(tw.JobKey))
{
tw.state = InternalTriggerState.Blocked;
}
else
{
timeTriggers.Add(tw);
}
}
}
/// <summary>
/// Remove (delete) the <see cref="ITrigger" /> with the
/// given name.
///
/// </summary>
/// <returns>
/// <see langword="true" /> if a <see cref="ITrigger" /> with the given
/// name and group was found and removed from the store.
/// </returns>
/// <param name="key">The <see cref="ITrigger" /> to be removed.</param>
/// <param name="removeOrphanedJob">Whether to delete orphaned job details from scheduler if job becomes orphaned from removing the trigger.</param>
protected virtual ValueTask<bool> RemoveTrigger(
TriggerKey key,
bool removeOrphanedJob)
{
return new ValueTask<bool>(RemoveTriggerInternal(key, removeOrphanedJob));
}
private bool RemoveTriggerInternal(TriggerKey key, bool removeOrphanedJob = true)
{
lock (lockObject)
{
// remove from triggers by FQN map
var found = triggersByKey.TryRemove(key, out var tw);
if (tw != null)
{
// remove from triggers by group
if (triggersByGroup.TryGetValue(key.Group, out var grpMap))
{
if (grpMap.Remove(key) && grpMap.Count == 0)
{
triggersByGroup.Remove(key.Group);
}
}
//remove from triggers by job
if (triggersByJob.TryGetValue(tw.JobKey, out var jobList))
{
if (jobList.Remove(tw) && jobList.Count == 0)
{
triggersByJob.Remove(tw.JobKey);
}
}
timeTriggers.Remove(tw);
if (removeOrphanedJob)
{
JobWrapper jw = jobsByKey[tw.JobKey];
var trigs = GetTriggersForJobInternal(tw.JobKey);
if (trigs.Length == 0 && !jw.JobDetail.Durable)
{
if (RemoveJobInternal(jw.Key))
{
signaler.NotifySchedulerListenersJobDeleted(jw.Key).ConfigureAwait(false).GetAwaiter().GetResult();
}
}
}
}
return found;
}
}
/// <summary>
/// Replaces the trigger.
/// </summary>
/// <param name="triggerKey">The <see cref="TriggerKey"/> of the <see cref="ITrigger" /> to be replaced.</param>
/// <param name="newTrigger">The new trigger.</param>
/// <param name="cancellationToken">The cancellation instruction.</param>
public virtual ValueTask<bool> ReplaceTrigger(
TriggerKey triggerKey,
IOperableTrigger newTrigger,
CancellationToken cancellationToken = default)
{
bool found;
lock (lockObject)
{
// remove from triggers by FQN map
triggersByKey.TryRemove(triggerKey, out var tw);
found = tw != null;
if (found)
{
if (!tw!.JobKey.Equals(newTrigger.JobKey))
{
ThrowHelper.ThrowJobPersistenceException("New trigger is not related to the same job as the old trigger.");
}
// remove from triggers by group
if (triggersByGroup.TryGetValue(triggerKey.Group, out var grpMap))
{
if (grpMap.Remove(triggerKey) && grpMap.Count == 0)
{
triggersByGroup.Remove(triggerKey.Group);
}
}
// remove from triggers by job
if (triggersByJob.TryGetValue(tw.JobKey, out var jobList))
{
if (jobList.Remove(tw) && jobList.Count == 0)
{
triggersByJob.Remove(tw.JobKey);
}
}
timeTriggers.Remove(tw);
try
{
StoreTriggerInternal(newTrigger, replaceExisting: false);
}
catch (JobPersistenceException)
{
StoreTriggerInternal(tw.Trigger, replaceExisting: false); // put previous trigger back...
throw;
}
}
}
return new ValueTask<bool>(found);
}
/// <summary>
/// Retrieve the <see cref="IJobDetail" /> for the given
/// <see cref="IJob" />.
/// </summary>
/// <returns>
/// The desired <see cref="IJob" />, or null if there is no match.
/// </returns>
public virtual ValueTask<IJobDetail?> RetrieveJob(
JobKey jobKey,
CancellationToken cancellationToken = default)
{
return new ValueTask<IJobDetail?>(RetrieveJobInternal(jobKey));
}
private IJobDetail? RetrieveJobInternal(JobKey jobKey)
{
jobsByKey.TryGetValue(jobKey, out var jw);
var job = jw?.JobDetail.Clone();
return job;
}
/// <summary>
/// Retrieve the given <see cref="ITrigger" />.
/// </summary>
/// <returns>
/// The desired <see cref="ITrigger" />, or null if there is no match.
/// </returns>
public virtual ValueTask<IOperableTrigger?> RetrieveTrigger(
TriggerKey triggerKey,
CancellationToken cancellationToken = default)
{
triggersByKey.TryGetValue(triggerKey, out var tw);
var trigger = (IOperableTrigger?) tw?.Trigger.Clone();
return new ValueTask<IOperableTrigger?>(trigger);
}
/// <summary>
/// Determine whether a <see cref="ICalendar" /> with the given identifier already
/// exists within the scheduler.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="calName">the identifier to check for</param>
/// <param name="cancellationToken">The cancellation instruction.</param>
/// <returns>true if a calendar exists with the given identifier</returns>
public ValueTask<bool> CalendarExists(
string calName,
CancellationToken cancellationToken = default)
{
return new ValueTask<bool>(calendarsByName.ContainsKey(calName));
}
/// <summary>
/// Determine whether a <see cref="IJob"/> with the given identifier already
/// exists within the scheduler.
/// </summary>
/// <param name="jobKey">the identifier to check for</param>
/// <param name="cancellationToken">The cancellation instruction.</param>
/// <returns>true if a Job exists with the given identifier</returns>
public ValueTask<bool> CheckExists(
JobKey jobKey,
CancellationToken cancellationToken = default)
{
return new ValueTask<bool>(jobsByKey.ContainsKey(jobKey));
}
/// <summary>
/// Determine whether a <see cref="IJob"/> with the given identifier already
/// exists within the scheduler.
/// </summary>
/// <param name="jobKey">the identifier to check for</param>
/// <returns>
/// <see langword="true"/> if a job exists with the given identifier; otherwise <see langword="false"/>.
/// </returns>
private bool CheckExistsInternal(JobKey jobKey)
{
return jobsByKey.ContainsKey(jobKey);
}
/// <summary>
/// Determine whether a <see cref="ITrigger" /> with the given identifier already
/// exists within the scheduler.
/// </summary>
/// <param name="triggerKey">triggerKey the identifier to check for</param>
/// <param name="cancellationToken">The cancellation instruction.</param>
/// <returns>true if a Trigger exists with the given identifier</returns>
public ValueTask<bool> CheckExists(
TriggerKey triggerKey,
CancellationToken cancellationToken = default)
{
return new ValueTask<bool>(triggersByKey.ContainsKey(triggerKey));
}
/// <summary>
/// Get the current state of the identified <see cref="ITrigger" />.
/// </summary>
/// <seealso cref="TriggerState.Normal" />
/// <seealso cref="TriggerState.Paused" />
/// <seealso cref="TriggerState.Complete" />
/// <seealso cref="TriggerState.Error" />
/// <seealso cref="TriggerState.Blocked" />
/// <seealso cref="TriggerState.None"/>
public virtual ValueTask<TriggerState> GetTriggerState(
TriggerKey triggerKey,
CancellationToken cancellationToken = default)
{
triggersByKey.TryGetValue(triggerKey, out var tw);
if (tw == null)
{
return new ValueTask<TriggerState>(TriggerState.None);
}
if (tw.state == InternalTriggerState.Complete)
{
return new ValueTask<TriggerState>(TriggerState.Complete);
}
if (tw.state == InternalTriggerState.Paused)
{
return new ValueTask<TriggerState>(TriggerState.Paused);
}
if (tw.state == InternalTriggerState.PausedAndBlocked)
{
return new ValueTask<TriggerState>(TriggerState.Paused);
}
if (tw.state == InternalTriggerState.Blocked)
{
return new ValueTask<TriggerState>(TriggerState.Blocked);
}
if (tw.state == InternalTriggerState.Error)
{
return new ValueTask<TriggerState>(TriggerState.Error);
}
return new ValueTask<TriggerState>(TriggerState.Normal);
}
public ValueTask<object> ResetTriggerFromErrorState(TriggerKey triggerKey, CancellationToken cancellationToken = default)
{
lock (lockObject)
{
// does the trigger exist?
if (!triggersByKey.TryGetValue(triggerKey, out var tw) || tw.Trigger == null)
{
return default;
}
// is the trigger in error state?
if (tw.state != InternalTriggerState.Error)
{
return default;
}
if (pausedTriggerGroups.Contains(triggerKey.Group))
{
tw.state = InternalTriggerState.Paused;
}
else
{
tw.state = InternalTriggerState.Waiting;
timeTriggers.Add(tw);
}
}
return default;
}
/// <summary>
/// Store the given <see cref="ICalendar" />.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="calendar">The <see cref="ICalendar" /> to be stored.</param>
/// <param name="replaceExisting">If <see langword="true" />, any <see cref="ICalendar" /> existing
/// in the <see cref="IJobStore" /> with the same name and group
/// should be over-written.</param>
/// <param name="updateTriggers">If <see langword="true" />, any <see cref="ITrigger" />s existing
/// in the <see cref="IJobStore" /> that reference an existing
/// Calendar with the same name with have their next fire time
/// re-computed with the new <see cref="ICalendar" />.</param>
/// <param name="cancellationToken">The cancellation instruction.</param>
public virtual ValueTask StoreCalendar(
string name,
ICalendar calendar,
bool replaceExisting,
bool updateTriggers,
CancellationToken cancellationToken = default)
{
calendar = calendar.Clone();
lock (lockObject)
{
calendarsByName.TryGetValue(name, out var obj);
if (obj != null && replaceExisting == false)
{
ThrowHelper.ThrowObjectAlreadyExistsException($"Calendar with name '{name}' already exists.");
}
if (obj != null)
{
calendarsByName.Remove(name);
}
calendarsByName[name] = calendar;
if (obj != null && updateTriggers)
{
IEnumerable<TriggerWrapper> trigs = GetTriggerWrappersForCalendar(name);
foreach (TriggerWrapper tw in trigs)
{
bool removed = timeTriggers.Remove(tw);
tw.Trigger.UpdateWithNewCalendar(calendar, MisfireThreshold);
if (removed)
{
timeTriggers.Add(tw);
}
}
}
}
return default;
}
/// <summary>
/// Remove (delete) the <see cref="ICalendar" /> with the
/// given name.
/// <para>
/// If removal of the <see cref="ICalendar" /> would result in
/// <see cref="ITrigger" />s pointing to non-existent calendars, then a
/// <see cref="JobPersistenceException" /> will be thrown.</para>
/// </summary>
/// <param name="calName">The name of the <see cref="ICalendar" /> to be removed.</param>
/// <param name="cancellationToken">The cancellation instruction.</param>
/// <returns>
/// <see langword="true" /> if a <see cref="ICalendar" /> with the given name
/// was found and removed from the store.
/// </returns>
public virtual ValueTask<bool> RemoveCalendar(
string calName,
CancellationToken cancellationToken = default)
{
return new ValueTask<bool>(RemoveCalendarInternal(calName));
}
private bool RemoveCalendarInternal(string calName)
{
lock (lockObject)
{
int numRefs = 0;
foreach (TriggerWrapper triggerWrapper in triggersByKey.Values)
{
IOperableTrigger trigg = triggerWrapper.Trigger;
if (trigg.CalendarName != null && trigg.CalendarName.Equals(calName))
{
numRefs++;
}
}
if (numRefs > 0)
{
ThrowHelper.ThrowJobPersistenceException("Calender cannot be removed if it referenced by a Trigger!");
}
return calendarsByName.Remove(calName);
}
}
/// <summary>
/// Retrieve the given <see cref="ITrigger" />.
/// </summary>
/// <param name="calName">The name of the <see cref="ICalendar" /> to be retrieved.</param>
/// <param name="cancellationToken">The cancellation instruction.</param>
/// <returns>
/// The desired <see cref="ICalendar" />, or null if there is no match.
/// </returns>
public virtual ValueTask<ICalendar?> RetrieveCalendar(
string calName,
CancellationToken cancellationToken = default)
{
calendarsByName.TryGetValue(calName, out var calendar);
calendar = calendar?.Clone();
return new ValueTask<ICalendar?>(calendar);
}
/// <summary>
/// Get the number of <see cref="IJobDetail" /> s that are
/// stored in the <see cref="IJobStore" />.
/// </summary>
public virtual ValueTask<int> GetNumberOfJobs(CancellationToken cancellationToken = default)
{
return new ValueTask<int>(jobsByKey.Count);
}
/// <summary>
/// Get the number of <see cref="ITrigger" /> s that are
/// stored in the <see cref="IJobStore" />.
/// </summary>
public virtual ValueTask<int> GetNumberOfTriggers(CancellationToken cancellationToken = default)
{
lock (lockObject)
{
return new ValueTask<int>(triggersByKey.Count);
}
}
/// <summary>
/// Get the number of <see cref="ICalendar" /> s that are
/// stored in the <see cref="IJobStore" />.
/// </summary>
public virtual ValueTask<int> GetNumberOfCalendars(CancellationToken cancellationToken = default)
{
return new ValueTask<int>(calendarsByName.Count);
}
/// <summary>
/// Get the names of all of the <see cref="IJob" /> s that
/// match the given group matcher.
/// </summary>
public virtual ValueTask<IReadOnlyCollection<JobKey>> GetJobKeys(
GroupMatcher<JobKey> matcher,
CancellationToken cancellationToken = default)
{
return new ValueTask<IReadOnlyCollection<JobKey>>(GetJobKeysInternal(matcher));
}
private HashSet<JobKey> GetJobKeysInternal(GroupMatcher<JobKey> matcher)
{
lock (lockObject)
{
HashSet<JobKey> outList = new HashSet<JobKey>();
StringOperator op = matcher.CompareWithOperator;
string compareToValue = matcher.CompareToValue;
if (StringOperator.Equality.Equals(op))
{
if (jobsByGroup.TryGetValue(compareToValue, out var grpMap))
{
foreach (JobWrapper jw in grpMap.Values)
{
outList.Add(jw.JobDetail.Key);
}
}
}
else
{
foreach (KeyValuePair<string, Dictionary<JobKey, JobWrapper>> entry in jobsByGroup)
{
if (op.Evaluate(entry.Key, compareToValue))
{
foreach (JobWrapper jobWrapper in entry.Value.Values)
{
outList.Add(jobWrapper.JobDetail.Key);
}
}
}
}
return outList;
}
}
/// <summary>
/// Get the names of all of the <see cref="ICalendar" /> s
/// in the <see cref="IJobStore" />.
/// <para>
/// If there are no ICalendars in the given group name, the result should be
/// a zero-length array (not <see langword="null" />).
/// </para>
/// </summary>
public virtual ValueTask<IReadOnlyCollection<string>> GetCalendarNames(
CancellationToken cancellationToken = default)
{
return new ValueTask<IReadOnlyCollection<string>>(new List<string>(calendarsByName.Keys));
}