-
Notifications
You must be signed in to change notification settings - Fork 188
/
Quick.Threads.pas
2620 lines (2310 loc) · 74.1 KB
/
Quick.Threads.pas
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
{ ***************************************************************************
Copyright (c) 2016-2022 Kike Pérez
Unit : Quick.Threads
Description : Thread safe collections
Author : Kike Pérez
Version : 1.5
Created : 09/03/2018
Modified : 14/06/2022
This file is part of QuickLib: https://github.com/exilon/QuickLib
***************************************************************************
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.
*************************************************************************** }
unit Quick.Threads;
{$i QuickLib.inc}
interface
uses
Classes,
Types,
SysUtils,
DateUtils,
Quick.Commons,
//Quick.Chrono,
Quick.Value,
Quick.FaultControl,
{$IFNDEF FPC}
System.RTLConsts,
System.Generics.Collections,
System.SyncObjs;
{$ELSE}
RtlConsts,
Generics.Collections,
syncobjs;
{$ENDIF}
type
TThreadedQueueCS<T> = class
private
FQueue: array of T;
FQueueSize, FQueueOffset: Integer;
FQueueLock: TCriticalSection;
{$IFDEF FPC}
FQueueCondVar : TEventObject;
{$ELSE}
FQueueCondVar: TConditionVariableCS;
{$ENDIF}
FShutDown: Boolean;
FPushTimeout, FPopTimeout: Cardinal;
FTotalItemsPushed, FTotalItemsPopped: Cardinal;
public
constructor Create(AQueueDepth: Integer = 16; PushTimeout: Cardinal = INFINITE; PopTimeout: Cardinal = INFINITE);
destructor Destroy; override;
procedure Grow(ADelta: Integer);
function PushItem(const AItem: T): TWaitResult; overload;
function PushItem(const AItem: T; var AQueueSize: Integer): TWaitResult; overload;
function PopItem: T; overload;
function PopItem(var AQueueSize: Integer): T; overload;
function PopItem(var AQueueSize: Integer; var AItem: T): TWaitResult; overload;
function PopItem(var AItem: T): TWaitResult; overload;
procedure DoShutDown;
procedure Clear;
property QueueSize: Integer read FQueueSize;
property ShutDown: Boolean read FShutDown;
property TotalItemsPushed: Cardinal read FTotalItemsPushed;
property TotalItemsPopped: Cardinal read FTotalItemsPopped;
end;
TThreadedQueueList<T> = class
private
fQueue : TQueue<T>;
fQueueSize : Integer;
fQueueLock : TCriticalSection;
{$IFDEF FPC}
FQueueCondVar : TSimpleEvent;
{$ELSE}
FQueueCondVar: TConditionVariableCS;
{$ENDIF}
fShutDown : Boolean;
fPushTimeout : Cardinal;
fPopTimeout : Cardinal;
fTotalItemsPushed : Cardinal;
fTotalItemsPopped : Cardinal;
public
constructor Create(AQueueDepth: Integer = 10; PushTimeout: Cardinal = INFINITE; PopTimeout: Cardinal = INFINITE);
destructor Destroy; override;
procedure Grow(ADelta: Integer);
function PushItem(const AItem: T): TWaitResult; overload;
function PushItem(const AItem: T; var AQueueSize: Integer): TWaitResult; overload;
function PopItem: T; overload;
function PopItem(var AQueueSize: Integer): T; overload;
function PopItem(var AQueueSize: Integer; var AItem: T): TWaitResult; overload;
function PopItem(var AItem: T): TWaitResult; overload;
procedure DoShutDown;
property QueueSize: Integer read FQueueSize;
property ShutDown: Boolean read FShutDown;
property TotalItemsPushed: Cardinal read FTotalItemsPushed;
property TotalItemsPopped: Cardinal read FTotalItemsPopped;
end;
{$IFNDEF FPC}
TThreadObjectList<T: class> = class(TList<T>)
private
fList: TObjectList<T>;
fLock: TObject;
fDuplicates: TDuplicates;
function GetItem(aIndex : Integer) : T;
procedure SetItem(aIndex : Integer; aValue : T);
public
constructor Create(OwnedObjects : Boolean);
destructor Destroy; override;
property Items[Index : Integer] : T read GetItem write SetItem ; default;
procedure Add(const Item: T);
procedure Clear;
function LockList: TObjectList<T>;
procedure Remove(const Item: T); inline;
procedure RemoveItem(const Item: T; Direction: TDirection);
procedure UnlockList; inline;
property Duplicates: TDuplicates read fDuplicates write fDuplicates;
end;
{$ENDIF}
{$IFNDEF FPC}
TAnonExceptionProc = reference to procedure(aException : Exception);
TAnonProc = TProc;
{$ELSE}
TProc = procedure of object;
TAnonExceptionProc = procedure(aException : Exception) of object;
{$ENDIF}
TThreadWorkStatus = (wsRunning, wsDone, wsException);
TSimpleThread = class(TThread)
private
fExecuteProc : TProc;
{$IFNDEF FPC}
fTimeoutFlag : TLightweightEvent;
{$ELSE}
fTimeoutFlag : TSimpleEvent;
{$ENDIF}
public
constructor Create(aProc: TProc; aCreateSuspended, aFreeOnTerminate : Boolean);
destructor Destroy; override;
procedure Execute; override;
function WaitFor(const aTimeout : Cardinal) : TWaitResult; overload;
end;
TAdvThread = class(TThread)
private
fExecuteProc : TProc;
fExceptionProc : TAnonExceptionProc;
fTerminateProc : TProc;
fExecuteWithSync : Boolean;
fTerminateWithSync : Boolean;
procedure DoExecute;
procedure CallToTerminate;
protected
procedure DoTerminate; override;
public
constructor Create(aProc : TProc; aSynchronize : Boolean);
procedure OnException(aProc : TAnonExceptionProc);
procedure OnTerminate(aProc : TProc; aSynchronize : Boolean);
procedure Execute; override;
end;
IAnonymousThread = interface
procedure Start;
function OnException(aProc : TAnonExceptionProc) : IAnonymousThread;
function OnTerminate(aProc : TProc) : IAnonymousThread;
function OnTerminate_Sync(aProc : TProc) : IAnonymousThread;
end;
TAnonymousThread = class(TInterfacedObject,IAnonymousThread)
private
fThread : TAdvThread;
constructor Create(aProc : TProc; aSynchronize : Boolean);
public
class function Execute(aProc : TProc) : IAnonymousThread; overload;
class function Execute_Sync(aProc : TProc) : IAnonymousThread; overload;
procedure Start;
function OnException(aProc : TAnonExceptionProc) : IAnonymousThread;
function OnTerminate(aProc : TProc) : IAnonymousThread; overload;
function OnTerminate_Sync(aProc : TProc) : IAnonymousThread; overload;
end;
TParamValue = class
private
fName : string;
fValue : TFlexValue;
fOwned : Boolean;
public
constructor Create; overload;
constructor Create(const aName : string; aValue : TFlexValue; aOwnedValue : Boolean); overload;
constructor Create(const aName: string; aValue: TVarRec; aOwnedValue: Boolean); overload;
destructor Destroy; override;
property Name : string read fName write fName;
property Value : TFlexValue read fValue write fValue;
property Owned : Boolean read fOwned write fOwned;
end;
TParamList = TObjectList<TParamValue>;
TWorkTaskStatus = (wtsPending, wtsAssigned, wtsRunning, wtsDone, wtsException);
TScheduleMode = (smRunOnce, smRepeatMode);
TTimeMeasure = (tmDays, tmHours, tmMinutes, tmSeconds, tmMilliseconds);
ETaskAddError = class(Exception);
ETaskInitializationError = class(Exception);
ETaskExecutionError = class(Exception);
ETaskParamError = class(Exception);
ETaskSchedulerError = class(Exception);
ITask = interface
['{0182FD36-5A7C-4C00-BBF8-7CFB1E3F9BB1}']
function GetParam(aIndex : Integer) : TFlexValue; overload;
function GetParam(const aName : string) : TFlexValue; overload;
function GetParam2(aIndex : Integer) : PFlexValue;
procedure SetParam(aIndex : Integer; Value : TFlexValue); overload;
procedure SetParam(const aName : string; Value : TFlexValue); overload;
function TaskStatus : TWorkTaskStatus;
function GetNumWorker : Integer;
procedure SetNumWorker(Value : Integer);
function GetIdTask : Int64;
procedure SetIdTask(Value : Int64);
function GetResult : TFlexValue;
procedure SetResult(aValue : TFlexValue);
procedure DoExecute;
procedure DoException(aException : Exception);
procedure DoTerminate;
procedure Enable;
procedure Disable;
{$IFNDEF FPC}
property Param[index : Integer] : TFlexValue read GetParam write SetParam; default;
property Param[const Name : string] : TFlexValue read GetParam write SetParam; default;
{$ELSE}
property Param[index : Integer] : TFlexValue read GetParam write SetParam;
property ParamByName[const Name : string] : TFlexValue read GetParam write SetParam; default;
{$ENDIF}
property NumWorker : Integer read GetNumWorker write SetNumWorker;
property Result : TFlexValue read GetResult write SetResult;
property IdTask : Int64 read GetIdTask;
function Done : Boolean;
function Failed : Boolean;
function NumRetries : Integer;
function MaxRetries : Integer;
function LastException : Exception;
function CircuitBreaked : Boolean;
function IsEnabled : Boolean;
end;
{$IFNDEF FPC}
TTaskProc = reference to procedure(task : ITask);
TTaskExceptionProc = reference to procedure(task : ITask; aException : Exception);
TTaskRetryProc = reference to procedure(task : ITask; aException : Exception; var aStopRetries : Boolean);
{$ELSE}
TTaskProc = procedure(task : ITask) of object;
TTaskExceptionProc = procedure(task : ITask; aException : Exception) of object;
TTaskRetryProc = procedure(task : ITask; aException : Exception; var aStopRetries : Boolean) of object;
{$ENDIF}
IWorkTask = interface(ITask)
function OnInitialize(aTaskProc : TTaskProc) : IWorkTask;
function OnException(aTaskProc : TTaskExceptionProc) : IWorkTask;
function OnException_Sync(aTaskProc : TTaskExceptionProc) : IWorkTask;
function OnRetry(aTaskProc : TTaskRetryProc) : IWorkTask;
function OnTerminated(aTaskProc : TTaskProc) : IWorkTask;
function OnTerminated_Sync(aTaskProc : TTaskProc) : IWorkTask;
function Retry(aMaxRetries : Integer) : IWorkTask;
function RetryForever : IWorkTask;
function WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer) : IWorkTask; overload;
function WaitAndRetry(aWaitTimeArray : TArray<Integer>) : IWorkTask; overload;
function WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer; aWaitTimeMultiplierFactor : Double) : IWorkTask; overload;
function WaitAndRetryForever(aWaitTimeBetweenRetriesMS : Integer) : IWorkTask; overload;
function WaitAndRetryForever(aWaitTimeBetweenRetriesMS : Integer; aWaitTimeMultiplierFactor : Double) : IWorkTask; overload;
function SetParameter(const aName : string; aValue : TFlexValue; aOwned : Boolean) : IWorkTask; overload;
function SetParameter(const aName : string; aValue : TFlexValue) : IWorkTask; overload;
procedure Run;
end;
IScheduledTask = interface(ITask)
['{AE551638-ECDE-4F64-89BF-F07BFCB9C9F7}']
function OnInitialize(aTaskProc : TTaskProc) : IScheduledTask;
function OnException(aTaskProc : TTaskExceptionProc) : IScheduledTask;
function OnException_Sync(aTaskProc : TTaskExceptionProc) : IScheduledTask;
function OnRetry(aTaskProc : TTaskRetryProc) : IScheduledTask;
function OnTerminated(aTaskProc : TTaskProc) : IScheduledTask;
function OnTerminated_Sync(aTaskProc : TTaskProc) : IScheduledTask;
function OnExpired(aTaskProc : TTaskProc) : IScheduledTask;
function OnExpired_Sync(aTaskProc : TTaskProc) : IScheduledTask;
function Retry(aMaxRetries : Integer) : IScheduledTask;
function RetryForever : IScheduledTask;
function WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer) : IScheduledTask; overload;
function WaitAndRetry(aWaitTimeArray : TArray<Integer>) : IScheduledTask; overload;
function WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer; aWaitTimeMultiplierFactor : Double) : IScheduledTask; overload;
function WaitAndRetryForever(aWaitTimeBetweenRetriesMS : Integer) : IScheduledTask; overload;
function WaitAndRetryForever(aWaitTimeBetweenRetriesMS : Integer; aWaitTimeMultiplierFactor : Double) : IScheduledTask; overload;
function CheckSchedule : Boolean;
procedure DoExpire;
function GetTaskName : string;
function StartAt(aStartDate : TDateTime) : IScheduledTask;
function StartTodayAt(aHour, aMinute: Word; aSecond : Word = 0): IScheduledTask;
function StartTomorrowAt(aHour, aMinute: Word; aSecond : Word = 0): IScheduledTask;
function StartOnDayChange : IScheduledTask;
function StartNow : IScheduledTask;
function StartInMinutes(aMinutes : Word) : IScheduledTask;
function StartInSeconds(aSeconds : Word) : IScheduledTask;
procedure RunOnce;
procedure RepeatEvery(aInterval : Integer; aTimeMeasure : TTimeMeasure); overload;
procedure RepeatEvery(aInterval : Integer; aTimeMeasure : TTimeMeasure; aEndTime : TDateTime); overload;
procedure RepeatEvery(aInterval : Integer; aTimeMeasure : TTimeMeasure; aRepeatTimes : Integer); overload;
procedure RepeatEveryDay;
procedure RepeatEveryWeek;
function IsFinished : Boolean;
procedure Cancel;
property Name : string read GetTaskName;
function SetParameter(const aName : string; aValue : TFlexValue; aOwned : Boolean) : IScheduledTask; overload;
function SetParameter(const aName : string; aValue : TFlexValue) : IScheduledTask; overload;
end;
TTask = class(TInterfacedObject,ITask)
private
fIdTask : Int64;
fNumWorker : Integer;
fNumRetries : Integer;
fParamList : TParamList;
fInitializeProc : TTaskProc;
fExecuteProc : TTaskProc;
fExceptProc : TTaskExceptionProc;
fTerminateProc : TTaskProc;
fExpiredProc : TTaskProc;
fTaskStatus : TWorkTaskStatus;
fOwnedParams : Boolean;
fEnabled : Boolean;
fExecuteWithSync : Boolean;
fExceptionWithSync : Boolean;
fRetryProc : TTaskRetryProc;
fTerminateWithSync : Boolean;
fFaultControl : TFaultControl;
fCustomFaultPolicy : Boolean;
fResult : TFlexValue;
function GetParam(aIndex : Integer) : TFlexValue; overload;
function GetParam(const aName : string) : TFlexValue; overload;
function GetParam2(aIndex : Integer) : PFlexValue;
procedure SetParam(aIndex : Integer; Value : TFlexValue); overload;
procedure SetParam(const aName : string; Value : TFlexValue); overload;
procedure SetParam(const aName : string; Value : TFlexValue; aOwned : Boolean); overload;
procedure DoInitialize;
procedure DoExecute;
procedure DoException(aException : Exception);
procedure DoTerminate;
function GetNumWorker : Integer;
procedure SetNumWorker(Value : Integer);
function GetIdTask : Int64;
procedure SetIdTask(Value : Int64);
function GetResult : TFlexValue;
procedure SetResult(aValue : TFlexValue);
protected
property FaultControl : TFaultControl read fFaultControl write fFaultControl;
property CustomFaultPolicy : Boolean read fCustomFaultPolicy write fCustomFaultPolicy;
property ExecuteWithSync : Boolean read fExecuteWithSync write fExecuteWithSync;
property TerminateWithSync : Boolean read fTerminateWithSync write fTerminateWithSync;
property ExceptionWithSync : Boolean read fExceptionWithSync write fExceptionWithSync;
procedure DoRetry(aRaisedException : Exception; var vStopRetries : Boolean);
procedure SetFaultPolicy(aFaultPolicy : TFaultPolicy);
procedure SetRetryPolicy(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer; aWaitTimeMultiplierFactor : Double); overload;
procedure SetRetryPolicy(aWaitTimeMSArray : TArray<Integer>); overload;
public
constructor Create(aParamArray : array of const; aOwnedParams : Boolean; aTaskProc : TTaskProc); virtual;
destructor Destroy; override;
property IdTask : Int64 read GetIdTask;
property OwnedParams : Boolean read fOwnedParams write fOwnedParams;
function IsEnabled : Boolean;
function TaskStatus : TWorkTaskStatus;
function Done : Boolean;
function Failed : Boolean;
function NumRetries : Integer;
function MaxRetries : Integer;
function LastException : Exception;
function CircuitBreaked : Boolean;
procedure Disable;
procedure Enable;
end;
TWorkTask = class(TTask,IWorkTask)
public
function OnInitialize(aTaskProc : TTaskProc) : IWorkTask;
function OnException(aTaskProc : TTaskExceptionProc) : IWorkTask; virtual;
function OnException_Sync(aTaskProc : TTaskExceptionProc) : IWorkTask; virtual;
function OnTerminated(aTaskProc : TTaskProc) : IWorkTask; virtual;
function OnTerminated_Sync(aTaskProc : TTaskProc) : IWorkTask; virtual;
function OnRetry(aTaskProc : TTaskRetryProc) : IWorkTask; virtual;
function Retry(aMaxRetries : Integer) : IWorkTask;
function RetryForever : IWorkTask;
function WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer) : IWorkTask; overload;
function WaitAndRetry(aWaitTimeArray : TArray<Integer>) : IWorkTask; overload;
function WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer; aWaitTimeMultiplierFactor : Double) : IWorkTask; overload;
function WaitAndRetryForever(aWaitTimeBetweenRetriesMS : Integer) : IWorkTask; overload;
function WaitAndRetryForever(aWaitTimeBetweenRetriesMS : Integer; aWaitTimeMultiplierFactor : Double) : IWorkTask; overload;
function SetParameter(const aName : string; aValue : TFlexValue; aOwned : Boolean) : IWorkTask; overload;
function SetParameter(const aName : string; aValue : TFlexValue) : IWorkTask; overload;
procedure Run; virtual;
end;
TTaskQueue = TThreadedQueueCS<IWorkTask>;
TScheduledTask = class(TTask,IScheduledTask)
private
fName : string;
fExecutionTimes : Integer;
fScheduleMode : TScheduleMode;
fTimeInterval : Integer;
fTimeMeasure : TTimeMeasure;
fStartDate : TDateTime;
fLastExecution : TDateTime;
fNextExecution : TDateTime;
fExpirationDate : TDateTime;
fExpirationTimes : Integer;
fFinished : Boolean;
fExpireWithSync: Boolean;
procedure ClearSchedule;
function CheckSchedule : Boolean;
procedure DoExpire;
function GetTaskName : string;
function GetCurrentSchedule: TPair<TTimeMeasure, Integer>;
protected
property ExpireWithSync : Boolean read fExpireWithSync write fExpireWithSync;
public
property Name : string read fName write fName;
function OnInitialize(aTaskProc : TTaskProc) : IScheduledTask;
property CurrentSchedule : TPair<TTimeMeasure, Integer> read GetCurrentSchedule;
function OnException(aTaskProc : TTaskExceptionProc) : IScheduledTask; virtual;
function OnException_Sync(aTaskProc : TTaskExceptionProc) : IScheduledTask; virtual;
function OnRetry(aTaskProc : TTaskRetryProc) : IScheduledTask; virtual;
function OnTerminated(aTaskProc : TTaskProc) : IScheduledTask; virtual;
function OnTerminated_Sync(aTaskProc : TTaskProc) : IScheduledTask; virtual;
function OnExpired(aTaskProc : TTaskProc) : IScheduledTask; virtual;
function OnExpired_Sync(aTaskProc : TTaskProc) : IScheduledTask; virtual;
function StartAt(aStartDate : TDateTime) : IScheduledTask;
function StartTodayAt(aHour, aMinute: Word; aSecond : Word = 0): IScheduledTask;
function StartTomorrowAt(aHour, aMinute: Word; aSecond : Word = 0): IScheduledTask;
function StartOnDayChange : IScheduledTask;
function StartNow : IScheduledTask;
function StartInMinutes(aMinutes : Word) : IScheduledTask;
function StartInSeconds(aSeconds : Word) : IScheduledTask;
procedure RunOnce;
procedure RepeatEvery(aInterval : Integer; aTimeMeasure : TTimeMeasure); overload;
procedure RepeatEvery(aInterval : Integer; aTimeMeasure : TTimeMeasure; aEndTime : TDateTime); overload;
procedure RepeatEvery(aInterval : Integer; aTimeMeasure : TTimeMeasure; aRepeatTimes : Integer); overload;
procedure RepeatEveryDay;
procedure RepeatEveryWeek;
function Retry(aMaxRetries : Integer) : IScheduledTask;
function RetryForever : IScheduledTask;
function WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer) : IScheduledTask; overload;
function WaitAndRetry(aWaitTimeArray : TArray<Integer>) : IScheduledTask; overload;
function WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer; aWaitTimeMultiplierFactor : Double) : IScheduledTask; overload;
function WaitAndRetryForever(aWaitTimeBetweenRetriesMS : Integer) : IScheduledTask; overload;
function WaitAndRetryForever(aWaitTimeBetweenRetriesMS : Integer; aWaitTimeMultiplierFactor : Double) : IScheduledTask; overload;
function SetParameter(const aName : string; aValue : TFlexValue; aOwned : Boolean) : IScheduledTask; overload;
function SetParameter(const aName : string; aValue : TFlexValue) : IScheduledTask; overload;
function IsFinished : Boolean;
procedure Cancel;
end;
TWorkerStatus = (wsIdle, wsWorking, wsSuspended);
TWorker = class(TThread)
protected
fStatus : TWorkerStatus;
fCurrentTask : ITask;
fDefaultFaultPolicy : TFaultPolicy;
procedure ExecuteTask;
procedure TerminateTask;
public
constructor Create;
destructor Destroy; override;
property Status : TWorkerStatus read fStatus;
procedure SetFaultPolicy(aTask : TTask);
procedure Execute; override;
end;
TSimpleWorker = class(TWorker)
private
fRunOnce : Boolean;
public
constructor Create(aTask : ITask; aRunOnce : Boolean = True);
procedure Execute; override;
end;
TQueueWorker = class(TWorker)
private
fCurrentIdTask : Integer;
fNumWorker : Integer;
fTaskQueue : TTaskQueue;
public
constructor Create(aNumWorker : Integer; aTaskQueue : TTaskQueue);
property NumWorker : Integer read fNumWorker;
procedure Execute; override;
end;
TScheduledWorker = class(TWorker)
private
procedure ExpireTask;
public
constructor Create(aNumWorker : Integer; aScheduledTask: IScheduledTask);
procedure Execute; override;
end;
TWorkerPool = TObjectList<TWorker>;
TRunTask = class
public
class function Execute(aTaskProc: TTaskProc): IWorkTask; overload;
class function Execute(aParamArray: array of const; aOwnedParams: Boolean; aTaskProc: TTaskProc): IWorkTask; overload;
class function Execute_Sync(aTaskProc: TTaskProc): IWorkTask; overload;
class function Execute_Sync(aParamArray: array of const; aOwnedParams: Boolean; aTaskProc: TTaskProc): IWorkTask; overload;
end;
IAsyncTask = interface
['{90A27D06-6FCD-493C-8AA0-C52C5105ED8B}']
procedure Wait; overload;
procedure Wait(const aTimeout : Cardinal); overload;
end;
TAsyncTask = class(TInterfacedObject,IAsyncTask)
private
fProcess : TSimpleThread;
constructor Create(aAction : TProc);
public
class function Run(const aAction : TProc) : IAsyncTask; virtual;
procedure Wait; overload;
procedure Wait(const aTimeout : Cardinal); overload;
destructor Destroy; override;
end;
{$IFNDEF FPC}
IAsyncTask<T> = interface
['{8529BBD4-B5AD-4674-8E42-3C74F5156A97}']
function Result : T; overload;
function Result(const aTimeout : Cardinal) : T; overload;
end;
TAsyncTask<T> = class(TInterfacedObject,IAsyncTask<T>)
private
fProcess : TSimpleThread;
fTaskResult : T;
fWaitForResult : Boolean;
function Result : T; overload;
function Result(const aTimeout : Cardinal) : T; overload;
constructor Create(aAction : TFunc<T>);
public
class function Run(const aAction : TFunc<T>) : IAsyncTask<T>; virtual;
destructor Destroy; override;
end;
{$ENDIF}
TBackgroundTasks = class
private
fMaxQueue : Integer;
fWorkerPool : TWorkerPool;
fConcurrentWorkers : Integer;
fInsertTimeout : Cardinal;
fExtractTimeout : Cardinal;
fTaskQueue : TTaskQueue;
fNumPushedTasks : Int64;
function GetTaskQueue : Cardinal;
public
constructor Create(aConcurrentWorkers : Integer; aInitialQueueSize : Integer = 100);
destructor Destroy; override;
property MaxQueue : Integer read fMaxQueue write fMaxQueue;
property InsertTimeout : Cardinal read fInsertTimeout write fInsertTimeout;
property ExtractTimeout : Cardinal read fExtractTimeout write fExtractTimeout;
property TaskQueued : Cardinal read GetTaskQueue;
property NumPushedTasks : Int64 read fNumPushedTasks;
property ConcurrentWorkers : Integer read fConcurrentWorkers write fConcurrentWorkers;
function AddTask(aTaskProc : TTaskProc) : IWorkTask; overload;
function AddTask_Sync(aTaskProc : TTaskProc) : IWorkTask; overload;
function AddTask(aParamArray : array of const; aOwnedParams : Boolean; aTaskProc : TTaskProc) : IWorkTask; overload;
function AddTask_Sync(aParamArray : array of const; aOwnedParams : Boolean; aTaskProc : TTaskProc) : IWorkTask; overload;
procedure Start;
procedure CancelAll;
end;
TScheduledTaskList = TList<IScheduledTask>;
TScheduler = class(TThread)
private
fListLock : TCriticalSection;
fCondVar : TSimpleEvent;
fTaskList : TScheduledTaskList;
fRemoveTaskAfterExpiration : Boolean;
public
constructor Create(aTaskList : TScheduledTaskList);
destructor Destroy; override;
property RemoveTaskAfterExpiration : Boolean read fRemoveTaskAfterExpiration write fRemoveTaskAfterExpiration;
procedure Execute; override;
function Add(aTask : TScheduledTask) : Integer;
function Get(aIdTask : Int64) : IScheduledTask; overload;
function Get(const aTaskName : string) : IScheduledTask; overload;
end;
TScheduledTasks = class
private
fTaskList : TScheduledTaskList;
fScheduler : TScheduler;
fNumPushedTasks : Int64;
fRemoveTaskAfterExpiration : Boolean;
fIsStarted : Boolean;
fFaultPolicy : TFaultPolicy;
public
constructor Create;
destructor Destroy; override;
property NumPushedTasks : Int64 read fNumPushedTasks;
property RemoveTaskAfterExpiration : Boolean read fRemoveTaskAfterExpiration write fRemoveTaskAfterExpiration;
property IsStarted : Boolean read fIsStarted;
property FaultPolicy : TFaultPolicy read fFaultPolicy write fFaultPolicy;
function AddTask(const aTaskName : string; aTaskProc : TTaskProc) : IScheduledTask; overload;
function AddTask_Sync(const aTaskName : string; aTaskProc : TTaskProc) : IScheduledTask; overload;
function AddTask(const aTaskName : string; aParamArray : array of const; aOwnedParams : Boolean; aTaskProc : TTaskProc) : IScheduledTask; overload;
function AddTask_Sync(const aTaskName : string; aParamArray : array of const; aOwnedParams : Boolean; aTaskProc : TTaskProc) : IScheduledTask; overload;
function GetTask(aIdTask : Int64) : IScheduledTask; overload;
function GetTask(const aTaskName : string) : IScheduledTask; overload;
procedure Start;
procedure Stop;
end;
TBackgroundWorkers = class
private
fWorkerPool : TWorkerPool;
fConcurrentWorkers : Integer;
fWorkerInitProc : TTaskProc;
fWorkerExecuteProc : TTaskProc;
fWorkerRetryProc : TTaskRetryProc;
fWorkerExceptionProc : TTaskExceptionProc;
fWorkerTerminateProc : TTaskProc;
fFaultPolicy : TFaultPolicy;
procedure SetRetryPolicy(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer; aWaitTimeMultiplierFactor: Double);
public
constructor Create(aConcurrentWorkers : Integer; aWorkerProc : TTaskProc);
destructor Destroy; override;
property ConcurrentWorkers : Integer read fConcurrentWorkers;
function OnInitialize(aTaskProc : TTaskProc) : TBackgroundWorkers;
function OnException(aTaskProc : TTaskExceptionProc) : TBackgroundWorkers;
function OnRetry(aTaskProc : TTaskRetryProc) : TBackgroundWorkers;
function OnTerminated(aTaskProc : TTaskProc) : TBackgroundWorkers;
function Retry(aMaxRetries : Integer) : TBackgroundWorkers;
function RetryForever : TBackgroundWorkers;
function WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer) : TBackgroundWorkers; overload;
function WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer; aWaitTimeMultiplierFactor : Double) : TBackgroundWorkers; overload;
function WaitAndRetryForever(aWaitTimeBetweenRetriesMS : Integer) : TBackgroundWorkers; overload;
function WaitAndRetryForever(aWaitTimeBetweenRetriesMS : Integer; aWaitTimeMultiplierFactor : Double) : TBackgroundWorkers; overload;
procedure Start;
procedure Stop;
end;
implementation
{ TThreadedQueueCS<T> }
procedure TThreadedQueueCS<T>.Clear;
var
obj : T;
begin
FQueueLock.Enter;
try
for obj in FQueue do
begin
if TypeInfo(T) = TypeInfo(TObject) then PObject(@obj){$ifndef FPC}{$IFDEF DELPHIRX12_UP}.Free{$ELSE}.DisposeOf{$ENDIF}{$ELSE}.Free{$ENDIF};
end;
SetLength(FQueue,0);
finally
FQueueLock.Leave;
end;
{$IFDEF FPC}
FQueueCondVar.SetEvent;
{$ELSE}
FQueueCondVar.ReleaseAll;
{$ENDIF}
end;
constructor TThreadedQueueCS<T>.Create(AQueueDepth: Integer = 16; PushTimeout: Cardinal = INFINITE; PopTimeout: Cardinal = INFINITE);
begin
inherited Create;
if AQueueDepth < 10 then raise Exception.Create('QueueDepth will be 10 or greater value');
SetLength(FQueue, AQueueDepth);
FQueueLock := TCriticalSection.Create;
{$IFDEF FPC}
FQueueCondVar := TEventObject.Create(nil, True, False, 'TQCS');
{$ELSE}
FQueueCondVar := TConditionVariableCS.Create;
{$ENDIF}
FPushTimeout := PushTimeout;
FPopTimeout := PopTimeout;
end;
destructor TThreadedQueueCS<T>.Destroy;
begin
DoShutDown;
FQueueLock.Free;
FQueueCondVar.Free;
inherited;
end;
procedure TThreadedQueueCS<T>.Grow(ADelta: Integer);
begin
FQueueLock.Enter;
try
SetLength(FQueue, Length(FQueue) + ADelta);
finally
FQueueLock.Leave;
end;
{$IFDEF FPC}
FQueueCondVar.SetEvent;
{$ELSE}
FQueueCondVar.ReleaseAll;
{$ENDIF}
end;
function TThreadedQueueCS<T>.PopItem: T;
var
LQueueSize: Integer;
begin
PopItem(LQueueSize, Result);
end;
function TThreadedQueueCS<T>.PopItem(var AQueueSize: Integer; var AItem: T): TWaitResult;
begin
AItem := Default(T);
FQueueLock.Enter;
try
Result := wrSignaled;
while (Result = wrSignaled) and (FQueueSize = 0) and not FShutDown do
begin
{$IFDEF FPC}
Result := FQueueCondVar.WaitFor(FPopTimeout);
{$ELSE}
Result := FQueueCondVar.WaitFor(FQueueLock, FPopTimeout);
{$ENDIF}
end;
if (FShutDown and (FQueueSize = 0)) or (Result <> wrSignaled) then Exit;
AItem := FQueue[FQueueOffset];
FQueue[FQueueOffset] := Default(T);
if FQueueSize = Length(FQueue) then
begin
{$IFDEF FPC}
FQueueCondVar.SetEvent;
{$ELSE}
FQueueCondVar.ReleaseAll;
{$ENDIF}
end;
Dec(FQueueSize);
Inc(FQueueOffset);
Inc(FTotalItemsPopped);
if FQueueOffset = Length(FQueue) then FQueueOffset := 0;
finally
AQueueSize := FQueueSize;
FQueueLock.Leave;
end;
end;
function TThreadedQueueCS<T>.PopItem(var AItem: T): TWaitResult;
var
LQueueSize: Integer;
begin
Result := PopItem(LQueueSize, AItem);
end;
function TThreadedQueueCS<T>.PopItem(var AQueueSize: Integer): T;
begin
PopItem(AQueueSize, Result);
end;
function TThreadedQueueCS<T>.PushItem(const AItem: T): TWaitResult;
var
LQueueSize: Integer;
begin
Result := PushItem(AItem, LQueueSize);
end;
function TThreadedQueueCS<T>.PushItem(const AItem: T; var AQueueSize: Integer): TWaitResult;
begin
FQueueLock.Enter;
try
if FQueueSize >= High(FQueue) then
begin
if FQueueSize < 1024 then Grow(FQueueSize)
else Grow(FQueueSize Div 2);
end;
Result := wrSignaled;
while (Result = wrSignaled) and (FQueueSize = Length(FQueue)) and not FShutDown do
begin
{$IFDEF FPC}
Result := FQueueCondVar.WaitFor(FPushTimeout);
{$ELSE}
Result := FQueueCondVar.WaitFor(FQueueLock, FPushTimeout);
{$ENDIF}
end;
if FShutDown or (Result <> wrSignaled) then Exit;
if FQueueSize = 0 then
begin
{$IFDEF FPC}
FQueueCondVar.SetEvent;
{$ELSE}
FQueueCondVar.ReleaseAll;
{$ENDIF}
end;
FQueue[(FQueueOffset + FQueueSize) mod Length(FQueue)] := AItem;
Inc(FQueueSize);
Inc(FTotalItemsPushed);
finally
AQueueSize := FQueueSize;
FQueueLock.Leave;
end;
end;
procedure TThreadedQueueCS<T>.DoShutDown;
begin
FShutDown := True;
{$IFDEF FPC}
FQueueCondVar.SetEvent;
{$ELSE}
FQueueCondVar.ReleaseAll;
{$ENDIF}
end;
{ TThreadedQueueList<T> }
constructor TThreadedQueueList<T>.Create(AQueueDepth: Integer = 10; PushTimeout: Cardinal = INFINITE; PopTimeout: Cardinal = INFINITE);
begin
inherited Create;
fQueue := TQueue<T>.Create;
fQueue.Capacity := AQueueDepth;
fQueueSize := 0;
fQueueLock := TCriticalSection.Create;
{$IFDEF FPC}
FQueueCondVar := TSimpleEvent.Create; //TEventObject.Create(nil, False, False, 'TQL');
{$ELSE}
fQueueCondVar := TConditionVariableCS.Create;
{$ENDIF}
fPushTimeout := PushTimeout;
fPopTimeout := PopTimeout;
end;
destructor TThreadedQueueList<T>.Destroy;
begin
DoShutDown;
fQueueCondVar.Free;
fQueueLock.Free;
//fQueueCondVar.Free;
fQueue.Free;
inherited;
end;
procedure TThreadedQueueList<T>.Grow(ADelta: Integer);
begin
fQueueLock.Enter;
try
fQueue.Capacity := fQueue.Capacity + ADelta;
finally
fQueueLock.Leave;
end;
{$IFDEF FPC}
FQueueCondVar.SetEvent;
{$ELSE}
FQueueCondVar.ReleaseAll;
{$ENDIF}
end;
function TThreadedQueueList<T>.PopItem: T;
var
LQueueSize: Integer;
begin
PopItem(LQueueSize, Result);
end;
{$IFDEF FPC}
function TThreadedQueueList<T>.PopItem(var AQueueSize: Integer; var AItem: T): TWaitResult;
//var
//crono : TChronometer;
begin
AItem := Default(T);
//crono := TChronometer.Create(False);
try
Result := wrSignaled;
//writeln('popitem');
//crono.Start;
while (Result = wrSignaled) and (fQueueSize = 0) and not fShutDown do
begin
//crono.Start;
Result := FQueueCondVar.WaitFor(FPopTimeout);
//crono.Stop;
//writeln('in: ' + crono.ElapsedTime);
//if result = twaitresult.wrError then result := twaitresult.wrError;
end;
//crono.Stop;
//writeln('out: ' + crono.ElapsedTime);
fQueueLock.Enter;
try
if (FShutDown and (fQueueSize = 0)) or (Result <> wrSignaled) then Exit;
AItem := fQueue.Extract;
Dec(FQueueSize);
Inc(fTotalItemsPopped);
finally
fQueueLock.Leave;
end;
finally
AQueueSize := fQueueSize;
end;
end;
{$ELSE}
function TThreadedQueueList<T>.PopItem(var AQueueSize: Integer; var AItem: T): TWaitResult;
begin
AItem := Default(T);
fQueueLock.Enter;
try
Result := wrSignaled;
while (Result = wrSignaled) and (fQueueSize = 0) and not fShutDown do
begin
Result := FQueueCondVar.WaitFor(FQueueLock, FPopTimeout);
end;
if (FShutDown and (fQueueSize = 0)) or (Result <> wrSignaled) then Exit;
AItem := fQueue.Extract;
if fQueueSize = fQueue.Count then
begin
FQueueCondVar.ReleaseAll;
end;
Dec(FQueueSize);
Inc(fTotalItemsPopped);
finally
AQueueSize := fQueueSize;
fQueueLock.Leave;
end;
end;
{$ENDIF}
function TThreadedQueueList<T>.PopItem(var AItem: T): TWaitResult;
var
LQueueSize: Integer;
begin
Result := PopItem(LQueueSize, AItem);
end;
function TThreadedQueueList<T>.PopItem(var AQueueSize: Integer): T;
begin
PopItem(AQueueSize, Result);
end;
function TThreadedQueueList<T>.PushItem(const AItem: T): TWaitResult;
var
LQueueSize: Integer;
begin
Result := PushItem(AItem, LQueueSize);
end;
{$IFDEF FPC}
function TThreadedQueueList<T>.PushItem(const AItem: T; var AQueueSize: Integer): TWaitResult;
begin
FQueueLock.Enter;
try
if FQueueSize >= fQueue.Count then Grow(10);
Result := wrSignaled;
//while (Result = wrSignaled) and (fQueueSize = fQueue.Count) and not fShutDown do