Quick.Threads.pas 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279
  1. { ***************************************************************************
  2. Copyright (c) 2016-2019 Kike Pérez
  3. Unit : Quick.Threads
  4. Description : Thread safe collections
  5. Author : Kike Pérez
  6. Version : 1.5
  7. Created : 09/03/2018
  8. Modified : 07/09/2019
  9. This file is part of QuickLib: https://github.com/exilon/QuickLib
  10. ***************************************************************************
  11. Licensed under the Apache License, Version 2.0 (the "License");
  12. you may not use this file except in compliance with the License.
  13. You may obtain a copy of the License at
  14. http://www.apache.org/licenses/LICENSE-2.0
  15. Unless required by applicable law or agreed to in writing, software
  16. distributed under the License is distributed on an "AS IS" BASIS,
  17. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18. See the License for the specific language governing permissions and
  19. limitations under the License.
  20. *************************************************************************** }
  21. unit Quick.Threads;
  22. {$i QuickLib.inc}
  23. interface
  24. uses
  25. Classes,
  26. Types,
  27. SysUtils,
  28. DateUtils,
  29. Quick.Commons,
  30. //Quick.Chrono,
  31. Quick.Value,
  32. Quick.FaultControl,
  33. {$IFNDEF FPC}
  34. System.RTLConsts,
  35. System.Generics.Collections,
  36. System.SyncObjs;
  37. {$ELSE}
  38. RtlConsts,
  39. Generics.Collections,
  40. syncobjs;
  41. {$ENDIF}
  42. type
  43. TThreadedQueueCS<T> = class
  44. private
  45. FQueue: array of T;
  46. FQueueSize, FQueueOffset: Integer;
  47. FQueueLock: TCriticalSection;
  48. {$IFDEF FPC}
  49. FQueueCondVar : TEventObject;
  50. {$ELSE}
  51. FQueueCondVar: TConditionVariableCS;
  52. {$ENDIF}
  53. FShutDown: Boolean;
  54. FPushTimeout, FPopTimeout: Cardinal;
  55. FTotalItemsPushed, FTotalItemsPopped: Cardinal;
  56. public
  57. constructor Create(AQueueDepth: Integer = 16; PushTimeout: Cardinal = INFINITE; PopTimeout: Cardinal = INFINITE);
  58. destructor Destroy; override;
  59. procedure Grow(ADelta: Integer);
  60. function PushItem(const AItem: T): TWaitResult; overload;
  61. function PushItem(const AItem: T; var AQueueSize: Integer): TWaitResult; overload;
  62. function PopItem: T; overload;
  63. function PopItem(var AQueueSize: Integer): T; overload;
  64. function PopItem(var AQueueSize: Integer; var AItem: T): TWaitResult; overload;
  65. function PopItem(var AItem: T): TWaitResult; overload;
  66. procedure DoShutDown;
  67. procedure Clear;
  68. property QueueSize: Integer read FQueueSize;
  69. property ShutDown: Boolean read FShutDown;
  70. property TotalItemsPushed: Cardinal read FTotalItemsPushed;
  71. property TotalItemsPopped: Cardinal read FTotalItemsPopped;
  72. end;
  73. TThreadedQueueList<T> = class
  74. private
  75. fQueue : TQueue<T>;
  76. fQueueSize : Integer;
  77. fQueueLock : TCriticalSection;
  78. {$IFDEF FPC}
  79. FQueueCondVar : TSimpleEvent;
  80. {$ELSE}
  81. FQueueCondVar: TConditionVariableCS;
  82. {$ENDIF}
  83. fShutDown : Boolean;
  84. fPushTimeout : Cardinal;
  85. fPopTimeout : Cardinal;
  86. fTotalItemsPushed : Cardinal;
  87. fTotalItemsPopped : Cardinal;
  88. public
  89. constructor Create(AQueueDepth: Integer = 10; PushTimeout: Cardinal = INFINITE; PopTimeout: Cardinal = INFINITE);
  90. destructor Destroy; override;
  91. procedure Grow(ADelta: Integer);
  92. function PushItem(const AItem: T): TWaitResult; overload;
  93. function PushItem(const AItem: T; var AQueueSize: Integer): TWaitResult; overload;
  94. function PopItem: T; overload;
  95. function PopItem(var AQueueSize: Integer): T; overload;
  96. function PopItem(var AQueueSize: Integer; var AItem: T): TWaitResult; overload;
  97. function PopItem(var AItem: T): TWaitResult; overload;
  98. procedure DoShutDown;
  99. property QueueSize: Integer read FQueueSize;
  100. property ShutDown: Boolean read FShutDown;
  101. property TotalItemsPushed: Cardinal read FTotalItemsPushed;
  102. property TotalItemsPopped: Cardinal read FTotalItemsPopped;
  103. end;
  104. {$IFNDEF FPC}
  105. TThreadObjectList<T: class> = class(TList<T>)
  106. private
  107. fList: TObjectList<T>;
  108. fLock: TObject;
  109. fDuplicates: TDuplicates;
  110. function GetItem(aIndex : Integer) : T;
  111. procedure SetItem(aIndex : Integer; aValue : T);
  112. public
  113. constructor Create(OwnedObjects : Boolean);
  114. destructor Destroy; override;
  115. property Items[Index : Integer] : T read GetItem write SetItem ; default;
  116. procedure Add(const Item: T);
  117. procedure Clear;
  118. function LockList: TObjectList<T>;
  119. procedure Remove(const Item: T); inline;
  120. procedure RemoveItem(const Item: T; Direction: TDirection);
  121. procedure UnlockList; inline;
  122. property Duplicates: TDuplicates read fDuplicates write fDuplicates;
  123. end;
  124. {$ENDIF}
  125. {$IFNDEF FPC}
  126. TAnonExceptionProc = reference to procedure(aException : Exception);
  127. TAnonProc = TProc;
  128. {$ELSE}
  129. TProc = procedure of object;
  130. TAnonExceptionProc = procedure(aException : Exception) of object;
  131. {$ENDIF}
  132. TThreadWorkStatus = (wsRunning, wsDone, wsException);
  133. TAdvThread = class(TThread)
  134. private
  135. fExecuteProc : TProc;
  136. fExceptionProc : TAnonExceptionProc;
  137. fTerminateProc : TProc;
  138. fExecuteWithSync : Boolean;
  139. fTerminateWithSync : Boolean;
  140. procedure DoExecute;
  141. procedure CallToTerminate;
  142. protected
  143. procedure DoTerminate; override;
  144. public
  145. constructor Create(aProc : TProc; aSynchronize : Boolean);
  146. procedure OnException(aProc : TAnonExceptionProc);
  147. procedure OnTerminate(aProc : TProc; aSynchronize : Boolean);
  148. procedure Execute; override;
  149. end;
  150. IAnonymousThread = interface
  151. procedure Start;
  152. function OnException(aProc : TAnonExceptionProc) : IAnonymousThread;
  153. function OnTerminate(aProc : TProc) : IAnonymousThread;
  154. function OnTerminate_Sync(aProc : TProc) : IAnonymousThread;
  155. end;
  156. TAnonymousThread = class(TInterfacedObject,IAnonymousThread)
  157. private
  158. fThread : TAdvThread;
  159. constructor Create(aProc : TProc; aSynchronize : Boolean);
  160. public
  161. class function Execute(aProc : TProc) : IAnonymousThread; overload;
  162. class function Execute_Sync(aProc : TProc) : IAnonymousThread; overload;
  163. procedure Start;
  164. function OnException(aProc : TAnonExceptionProc) : IAnonymousThread;
  165. function OnTerminate(aProc : TProc) : IAnonymousThread; overload;
  166. function OnTerminate_Sync(aProc : TProc) : IAnonymousThread; overload;
  167. end;
  168. TParamValue = class
  169. private
  170. fName : string;
  171. fValue : TFlexValue;
  172. fOwned : Boolean;
  173. public
  174. constructor Create; overload;
  175. constructor Create(const aName : string; aValue : TFlexValue; aOwnedValue : Boolean); overload;
  176. constructor Create(const aName: string; aValue: TVarRec; aOwnedValue: Boolean); overload;
  177. destructor Destroy; override;
  178. property Name : string read fName write fName;
  179. property Value : TFlexValue read fValue write fValue;
  180. property Owned : Boolean read fOwned write fOwned;
  181. end;
  182. TParamList = TObjectList<TParamValue>;
  183. TWorkTaskStatus = (wtsPending, wtsAssigned, wtsRunning, wtsDone, wtsException);
  184. TScheduleMode = (smRunOnce, smRepeatMode);
  185. TTimeMeasure = (tmDays, tmHours, tmMinutes, tmSeconds, tmMilliseconds);
  186. ETaskAddError = class(Exception);
  187. ETaskInitializationError = class(Exception);
  188. ETaskExecutionError = class(Exception);
  189. ETaskParamError = class(Exception);
  190. ETaskSchedulerError = class(Exception);
  191. ITask = interface
  192. ['{0182FD36-5A7C-4C00-BBF8-7CFB1E3F9BB1}']
  193. function GetParam(aIndex : Integer) : TFlexValue; overload;
  194. function GetParam(const aName : string) : TFlexValue; overload;
  195. function GetParam2(aIndex : Integer) : PFlexValue;
  196. procedure SetParam(aIndex : Integer; Value : TFlexValue); overload;
  197. procedure SetParam(const aName : string; Value : TFlexValue); overload;
  198. function TaskStatus : TWorkTaskStatus;
  199. function GetNumWorker : Integer;
  200. procedure SetNumWorker(Value : Integer);
  201. function GetIdTask : Int64;
  202. procedure SetIdTask(Value : Int64);
  203. function GetResult : TFlexValue;
  204. procedure SetResult(aValue : TFlexValue);
  205. procedure DoExecute;
  206. procedure DoException(aException : Exception);
  207. procedure DoTerminate;
  208. {$IFNDEF FPC}
  209. property Param[index : Integer] : TFlexValue read GetParam write SetParam; default;
  210. property Param[const Name : string] : TFlexValue read GetParam write SetParam; default;
  211. {$ELSE}
  212. property Param[index : Integer] : TFlexValue read GetParam write SetParam;
  213. property ParamByName[const Name : string] : TFlexValue read GetParam write SetParam; default;
  214. {$ENDIF}
  215. property NumWorker : Integer read GetNumWorker write SetNumWorker;
  216. property Result : TFlexValue read GetResult write SetResult;
  217. property IdTask : Int64 read GetIdTask;
  218. function Done : Boolean;
  219. function Failed : Boolean;
  220. function NumRetries : Integer;
  221. function MaxRetries : Integer;
  222. function LastException : Exception;
  223. function CircuitBreaked : Boolean;
  224. function IsEnabled : Boolean;
  225. end;
  226. {$IFNDEF FPC}
  227. TTaskProc = reference to procedure(task : ITask);
  228. TTaskExceptionProc = reference to procedure(task : ITask; aException : Exception);
  229. TTaskRetryProc = reference to procedure(task : ITask; aException : Exception; var aStopRetries : Boolean);
  230. {$ELSE}
  231. TTaskProc = procedure(task : ITask) of object;
  232. TTaskExceptionProc = procedure(task : ITask; aException : Exception) of object;
  233. TTaskRetryProc = procedure(task : ITask; aException : Exception; var aStopRetries : Boolean) of object;
  234. {$ENDIF}
  235. IWorkTask = interface(ITask)
  236. function OnInitialize(aTaskProc : TTaskProc) : IWorkTask;
  237. function OnException(aTaskProc : TTaskExceptionProc) : IWorkTask;
  238. function OnRetry(aTaskProc : TTaskRetryProc) : IWorkTask;
  239. function OnTerminated(aTaskProc : TTaskProc) : IWorkTask;
  240. function Retry(aMaxRetries : Integer) : IWorkTask;
  241. function RetryForever : IWorkTask;
  242. function WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer) : IWorkTask; overload;
  243. function WaitAndRetry(aWaitTimeArray : TArray<Integer>) : IWorkTask; overload;
  244. function WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer; aWaitTimeMultiplierFactor : Double) : IWorkTask; overload;
  245. function WaitAndRetryForever(aWaitTimeBetweenRetriesMS : Integer) : IWorkTask; overload;
  246. function WaitAndRetryForever(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer; aWaitTimeMultiplierFactor : Double) : IWorkTask; overload;
  247. function SetParameter(const aName : string; aValue : TFlexValue; aOwned : Boolean) : IWorkTask; overload;
  248. function SetParameter(const aName : string; aValue : TFlexValue) : IWorkTask; overload;
  249. procedure Run;
  250. end;
  251. IScheduledTask = interface(ITask)
  252. ['{AE551638-ECDE-4F64-89BF-F07BFCB9C9F7}']
  253. function OnInitialize(aTaskProc : TTaskProc) : IScheduledTask;
  254. function OnException(aTaskProc : TTaskExceptionProc) : IScheduledTask;
  255. function OnException_Sync(aTaskProc : TTaskExceptionProc) : IScheduledTask;
  256. function OnRetry(aTaskProc : TTaskRetryProc) : IScheduledTask;
  257. function OnTerminated(aTaskProc : TTaskProc) : IScheduledTask;
  258. function OnTerminated_Sync(aTaskProc : TTaskProc) : IScheduledTask;
  259. function OnExpired(aTaskProc : TTaskProc) : IScheduledTask;
  260. function OnExpired_Sync(aTaskProc : TTaskProc) : IScheduledTask;
  261. function Retry(aMaxRetries : Integer) : IScheduledTask;
  262. function RetryForever : IScheduledTask;
  263. function WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer) : IScheduledTask; overload;
  264. function WaitAndRetry(aWaitTimeArray : TArray<Integer>) : IScheduledTask; overload;
  265. function WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer; aWaitTimeMultiplierFactor : Double) : IScheduledTask; overload;
  266. function WaitAndRetryForever(aWaitTimeBetweenRetriesMS : Integer) : IScheduledTask; overload;
  267. function WaitAndRetryForever(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer; aWaitTimeMultiplierFactor : Double) : IScheduledTask; overload;
  268. function CheckSchedule : Boolean;
  269. procedure DoExpire;
  270. function GetTaskName : string;
  271. function StartAt(aStartDate : TDateTime) : IScheduledTask;
  272. function StartTodayAt(aHour, aMinute: Word; aSecond : Word = 0): IScheduledTask;
  273. function StartTomorrowAt(aHour, aMinute: Word; aSecond : Word = 0): IScheduledTask;
  274. function StartOnDayChange : IScheduledTask;
  275. function StartNow : IScheduledTask;
  276. function StartInMinutes(aMinutes : Word) : IScheduledTask;
  277. function StartInSeconds(aSeconds : Word) : IScheduledTask;
  278. procedure RunOnce;
  279. procedure RepeatEvery(aInterval : Integer; aTimeMeasure : TTimeMeasure); overload;
  280. procedure RepeatEvery(aInterval : Integer; aTimeMeasure : TTimeMeasure; aEndTime : TDateTime); overload;
  281. procedure RepeatEvery(aInterval : Integer; aTimeMeasure : TTimeMeasure; aRepeatTimes : Integer); overload;
  282. procedure RepeatEveryDay;
  283. procedure RepeatEveryWeek;
  284. function IsFinished : Boolean;
  285. procedure Cancel;
  286. property Name : string read GetTaskName;
  287. function SetParameter(const aName : string; aValue : TFlexValue; aOwned : Boolean) : IScheduledTask; overload;
  288. function SetParameter(const aName : string; aValue : TFlexValue) : IScheduledTask; overload;
  289. end;
  290. TTask = class(TInterfacedObject,ITask)
  291. private
  292. fIdTask : Int64;
  293. fNumWorker : Integer;
  294. fNumRetries : Integer;
  295. fParamList : TParamList;
  296. fInitializeProc : TTaskProc;
  297. fExecuteProc : TTaskProc;
  298. fExceptProc : TTaskExceptionProc;
  299. fTerminateProc : TTaskProc;
  300. fExpiredProc : TTaskProc;
  301. fTaskStatus : TWorkTaskStatus;
  302. fOwnedParams : Boolean;
  303. fEnabled : Boolean;
  304. fExecuteWithSync : Boolean;
  305. fExceptionWithSync : Boolean;
  306. fRetryProc : TTaskRetryProc;
  307. fTerminateWithSync : Boolean;
  308. fFaultControl : TFaultControl;
  309. fCustomFaultPolicy : Boolean;
  310. fResult : TFlexValue;
  311. function GetParam(aIndex : Integer) : TFlexValue; overload;
  312. function GetParam(const aName : string) : TFlexValue; overload;
  313. function GetParam2(aIndex : Integer) : PFlexValue;
  314. procedure SetParam(aIndex : Integer; Value : TFlexValue); overload;
  315. procedure SetParam(const aName : string; Value : TFlexValue); overload;
  316. procedure SetParam(const aName : string; Value : TFlexValue; aOwned : Boolean); overload;
  317. procedure DoInitialize;
  318. procedure DoExecute;
  319. procedure DoException(aException : Exception);
  320. procedure DoTerminate;
  321. function GetNumWorker : Integer;
  322. procedure SetNumWorker(Value : Integer);
  323. function GetIdTask : Int64;
  324. procedure SetIdTask(Value : Int64);
  325. function GetResult : TFlexValue;
  326. procedure SetResult(aValue : TFlexValue);
  327. protected
  328. property FaultControl : TFaultControl read fFaultControl write fFaultControl;
  329. property CustomFaultPolicy : Boolean read fCustomFaultPolicy write fCustomFaultPolicy;
  330. property ExecuteWithSync : Boolean read fExecuteWithSync write fExecuteWithSync;
  331. property TerminateWithSync : Boolean read fTerminateWithSync write fTerminateWithSync;
  332. property ExceptionWithSync : Boolean read fExceptionWithSync write fExceptionWithSync;
  333. procedure DoRetry(aRaisedException : Exception; var vStopRetries : Boolean);
  334. procedure SetFaultPolicy(aFaultPolicy : TFaultPolicy);
  335. procedure SetRetryPolicy(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer; aWaitTimeMultiplierFactor : Double); overload;
  336. procedure SetRetryPolicy(aWaitTimeMSArray : TArray<Integer>); overload;
  337. public
  338. constructor Create(aParamArray : array of const; aOwnedParams : Boolean; aTaskProc : TTaskProc); virtual;
  339. destructor Destroy; override;
  340. property IdTask : Int64 read GetIdTask;
  341. property OwnedParams : Boolean read fOwnedParams write fOwnedParams;
  342. function IsEnabled : Boolean;
  343. function TaskStatus : TWorkTaskStatus;
  344. function Done : Boolean;
  345. function Failed : Boolean;
  346. function NumRetries : Integer;
  347. function MaxRetries : Integer;
  348. function LastException : Exception;
  349. function CircuitBreaked : Boolean;
  350. end;
  351. TWorkTask = class(TTask,IWorkTask)
  352. public
  353. function OnInitialize(aTaskProc : TTaskProc) : IWorkTask;
  354. function OnException(aTaskProc : TTaskExceptionProc) : IWorkTask; virtual;
  355. function OnTerminated(aTaskProc : TTaskProc) : IWorkTask; virtual;
  356. function OnRetry(aTaskProc : TTaskRetryProc) : IWorkTask; virtual;
  357. function Retry(aMaxRetries : Integer) : IWorkTask;
  358. function RetryForever : IWorkTask;
  359. function WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer) : IWorkTask; overload;
  360. function WaitAndRetry(aWaitTimeArray : TArray<Integer>) : IWorkTask; overload;
  361. function WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer; aWaitTimeMultiplierFactor : Double) : IWorkTask; overload;
  362. function WaitAndRetryForever(aWaitTimeBetweenRetriesMS : Integer) : IWorkTask; overload;
  363. function WaitAndRetryForever(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer; aWaitTimeMultiplierFactor : Double) : IWorkTask; overload;
  364. function SetParameter(const aName : string; aValue : TFlexValue; aOwned : Boolean) : IWorkTask; overload;
  365. function SetParameter(const aName : string; aValue : TFlexValue) : IWorkTask; overload;
  366. procedure Run; virtual;
  367. end;
  368. TTaskQueue = TThreadedQueueCS<IWorkTask>;
  369. TScheduledTask = class(TTask,IScheduledTask)
  370. private
  371. fName : string;
  372. fExecutionTimes : Integer;
  373. fScheduleMode : TScheduleMode;
  374. fTimeInterval : Integer;
  375. fTimeMeasure : TTimeMeasure;
  376. fStartDate : TDateTime;
  377. fLastExecution : TDateTime;
  378. fNextExecution : TDateTime;
  379. fExpirationDate : TDateTime;
  380. fExpirationTimes : Integer;
  381. fFinished : Boolean;
  382. fExpireWithSync: Boolean;
  383. procedure ClearSchedule;
  384. function CheckSchedule : Boolean;
  385. procedure DoExpire;
  386. function GetTaskName : string;
  387. function GetCurrentSchedule: TPair<TTimeMeasure, Integer>;
  388. protected
  389. property ExpireWithSync : Boolean read fExpireWithSync write fExpireWithSync;
  390. public
  391. property Name : string read fName write fName;
  392. function OnInitialize(aTaskProc : TTaskProc) : IScheduledTask;
  393. property CurrentSchedule : TPair<TTimeMeasure, Integer> read GetCurrentSchedule;
  394. function OnException(aTaskProc : TTaskExceptionProc) : IScheduledTask; virtual;
  395. function OnException_Sync(aTaskProc : TTaskExceptionProc) : IScheduledTask; virtual;
  396. function OnRetry(aTaskProc : TTaskRetryProc) : IScheduledTask; virtual;
  397. function OnTerminated(aTaskProc : TTaskProc) : IScheduledTask; virtual;
  398. function OnTerminated_Sync(aTaskProc : TTaskProc) : IScheduledTask; virtual;
  399. function OnExpired(aTaskProc : TTaskProc) : IScheduledTask; virtual;
  400. function OnExpired_Sync(aTaskProc : TTaskProc) : IScheduledTask; virtual;
  401. function StartAt(aStartDate : TDateTime) : IScheduledTask;
  402. function StartTodayAt(aHour, aMinute: Word; aSecond : Word = 0): IScheduledTask;
  403. function StartTomorrowAt(aHour, aMinute: Word; aSecond : Word = 0): IScheduledTask;
  404. function StartOnDayChange : IScheduledTask;
  405. function StartNow : IScheduledTask;
  406. function StartInMinutes(aMinutes : Word) : IScheduledTask;
  407. function StartInSeconds(aSeconds : Word) : IScheduledTask;
  408. procedure RunOnce;
  409. procedure RepeatEvery(aInterval : Integer; aTimeMeasure : TTimeMeasure); overload;
  410. procedure RepeatEvery(aInterval : Integer; aTimeMeasure : TTimeMeasure; aEndTime : TDateTime); overload;
  411. procedure RepeatEvery(aInterval : Integer; aTimeMeasure : TTimeMeasure; aRepeatTimes : Integer); overload;
  412. procedure RepeatEveryDay;
  413. procedure RepeatEveryWeek;
  414. function Retry(aMaxRetries : Integer) : IScheduledTask;
  415. function RetryForever : IScheduledTask;
  416. function WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer) : IScheduledTask; overload;
  417. function WaitAndRetry(aWaitTimeArray : TArray<Integer>) : IScheduledTask; overload;
  418. function WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer; aWaitTimeMultiplierFactor : Double) : IScheduledTask; overload;
  419. function WaitAndRetryForever(aWaitTimeBetweenRetriesMS : Integer) : IScheduledTask; overload;
  420. function WaitAndRetryForever(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer; aWaitTimeMultiplierFactor : Double) : IScheduledTask; overload;
  421. function SetParameter(const aName : string; aValue : TFlexValue; aOwned : Boolean) : IScheduledTask; overload;
  422. function SetParameter(const aName : string; aValue : TFlexValue) : IScheduledTask; overload;
  423. function IsFinished : Boolean;
  424. procedure Cancel;
  425. end;
  426. TWorkerStatus = (wsIdle, wsWorking, wsSuspended);
  427. TWorker = class(TThread)
  428. protected
  429. fStatus : TWorkerStatus;
  430. fCurrentTask : ITask;
  431. fDefaultFaultPolicy : TFaultPolicy;
  432. procedure ExecuteTask;
  433. procedure TerminateTask;
  434. public
  435. constructor Create;
  436. destructor Destroy; override;
  437. property Status : TWorkerStatus read fStatus;
  438. procedure SetFaultPolicy(aTask : TTask);
  439. procedure Execute; override;
  440. end;
  441. TSimpleWorker = class(TWorker)
  442. public
  443. constructor Create(aTask : ITask);
  444. procedure Execute; override;
  445. end;
  446. TQueueWorker = class(TWorker)
  447. private
  448. fCurrentIdTask : Integer;
  449. fNumWorker : Integer;
  450. fTaskQueue : TTaskQueue;
  451. public
  452. constructor Create(aNumWorker : Integer; aTaskQueue : TTaskQueue);
  453. property NumWorker : Integer read fNumWorker;
  454. procedure Execute; override;
  455. end;
  456. TScheduledWorker = class(TWorker)
  457. private
  458. procedure ExpireTask;
  459. public
  460. constructor Create(aNumWorker : Integer; aScheduledTask: IScheduledTask);
  461. procedure Execute; override;
  462. end;
  463. TWorkerPool = TObjectList<TWorker>;
  464. TRunTask = class
  465. public
  466. class function Execute(aTaskProc: TTaskProc): IWorkTask; overload;
  467. class function Execute(aParamArray: array of const; aOwnedParams: Boolean; aTaskProc: TTaskProc): IWorkTask; overload;
  468. class function Execute_Sync(aTaskProc: TTaskProc): IWorkTask; overload;
  469. class function Execute_Sync(aParamArray: array of const; aOwnedParams: Boolean; aTaskProc: TTaskProc): IWorkTask; overload;
  470. end;
  471. TBackgroundTasks = class
  472. private
  473. fMaxQueue : Integer;
  474. fWorkerPool : TWorkerPool;
  475. fConcurrentWorkers : Integer;
  476. fInsertTimeout : Cardinal;
  477. fExtractTimeout : Cardinal;
  478. fTaskQueue : TTaskQueue;
  479. fNumPushedTasks : Int64;
  480. function GetTaskQueue : Cardinal;
  481. public
  482. constructor Create(aConcurrentWorkers : Integer; aInitialQueueSize : Integer = 100);
  483. destructor Destroy; override;
  484. property MaxQueue : Integer read fMaxQueue write fMaxQueue;
  485. property InsertTimeout : Cardinal read fInsertTimeout write fInsertTimeout;
  486. property ExtractTimeout : Cardinal read fExtractTimeout write fExtractTimeout;
  487. property TaskQueued : Cardinal read GetTaskQueue;
  488. property NumPushedTasks : Int64 read fNumPushedTasks;
  489. property ConcurrentWorkers : Integer read fConcurrentWorkers write fConcurrentWorkers;
  490. function AddTask(aTaskProc : TTaskProc) : IWorkTask; overload;
  491. function AddTask_Sync(aTaskProc : TTaskProc) : IWorkTask; overload;
  492. function AddTask(aParamArray : array of const; aOwnedParams : Boolean; aTaskProc : TTaskProc) : IWorkTask; overload;
  493. function AddTask_Sync(aParamArray : array of const; aOwnedParams : Boolean; aTaskProc : TTaskProc) : IWorkTask; overload;
  494. procedure Start;
  495. procedure CancelAll;
  496. end;
  497. TScheduledTaskList = TList<IScheduledTask>;
  498. TScheduler = class(TThread)
  499. private
  500. fListLock : TCriticalSection;
  501. fCondVar : TSimpleEvent;
  502. fTaskList : TScheduledTaskList;
  503. fRemoveTaskAfterExpiration : Boolean;
  504. public
  505. constructor Create(aTaskList : TScheduledTaskList);
  506. destructor Destroy; override;
  507. property RemoveTaskAfterExpiration : Boolean read fRemoveTaskAfterExpiration write fRemoveTaskAfterExpiration;
  508. procedure Execute; override;
  509. function Add(aTask : TScheduledTask) : Integer;
  510. function Get(aIdTask : Int64) : IScheduledTask; overload;
  511. function Get(const aTaskName : string) : IScheduledTask; overload;
  512. end;
  513. TScheduledTasks = class
  514. private
  515. fTaskList : TScheduledTaskList;
  516. fScheduler : TScheduler;
  517. fNumPushedTasks : Int64;
  518. fRemoveTaskAfterExpiration : Boolean;
  519. fIsStarted : Boolean;
  520. fFaultPolicy : TFaultPolicy;
  521. public
  522. constructor Create;
  523. destructor Destroy; override;
  524. property NumPushedTasks : Int64 read fNumPushedTasks;
  525. property RemoveTaskAfterExpiration : Boolean read fRemoveTaskAfterExpiration write fRemoveTaskAfterExpiration;
  526. property IsStarted : Boolean read fIsStarted;
  527. property FaultPolicy : TFaultPolicy read fFaultPolicy write fFaultPolicy;
  528. function AddTask(const aTaskName : string; aTaskProc : TTaskProc) : IScheduledTask; overload;
  529. function AddTask_Sync(const aTaskName : string; aTaskProc : TTaskProc) : IScheduledTask; overload;
  530. function AddTask(const aTaskName : string; aParamArray : array of const; aOwnedParams : Boolean; aTaskProc : TTaskProc) : IScheduledTask; overload;
  531. function AddTask_Sync(const aTaskName : string; aParamArray : array of const; aOwnedParams : Boolean; aTaskProc : TTaskProc) : IScheduledTask; overload;
  532. function GetTask(aIdTask : Int64) : IScheduledTask; overload;
  533. function GetTask(const aTaskName : string) : IScheduledTask; overload;
  534. procedure Start;
  535. procedure Stop;
  536. end;
  537. implementation
  538. { TThreadedQueueCS<T> }
  539. procedure TThreadedQueueCS<T>.Clear;
  540. var
  541. obj : T;
  542. begin
  543. FQueueLock.Enter;
  544. try
  545. for obj in FQueue do
  546. begin
  547. if TypeInfo(T) = TypeInfo(TObject) then PObject(@obj){$IFNDEF FPC}.DisposeOf;{$ELSE}.Free;{$ENDIF}
  548. end;
  549. SetLength(FQueue,0);
  550. finally
  551. FQueueLock.Leave;
  552. end;
  553. {$IFDEF FPC}
  554. FQueueCondVar.SetEvent;
  555. {$ELSE}
  556. FQueueCondVar.ReleaseAll;
  557. {$ENDIF}
  558. end;
  559. constructor TThreadedQueueCS<T>.Create(AQueueDepth: Integer = 16; PushTimeout: Cardinal = INFINITE; PopTimeout: Cardinal = INFINITE);
  560. begin
  561. inherited Create;
  562. if AQueueDepth < 10 then raise Exception.Create('QueueDepth will be 10 or greater value');
  563. SetLength(FQueue, AQueueDepth);
  564. FQueueLock := TCriticalSection.Create;
  565. {$IFDEF FPC}
  566. FQueueCondVar := TEventObject.Create(nil, True, False, 'TQCS');
  567. {$ELSE}
  568. FQueueCondVar := TConditionVariableCS.Create;
  569. {$ENDIF}
  570. FPushTimeout := PushTimeout;
  571. FPopTimeout := PopTimeout;
  572. end;
  573. destructor TThreadedQueueCS<T>.Destroy;
  574. begin
  575. DoShutDown;
  576. FQueueLock.Free;
  577. FQueueCondVar.Free;
  578. inherited;
  579. end;
  580. procedure TThreadedQueueCS<T>.Grow(ADelta: Integer);
  581. begin
  582. FQueueLock.Enter;
  583. try
  584. SetLength(FQueue, Length(FQueue) + ADelta);
  585. finally
  586. FQueueLock.Leave;
  587. end;
  588. {$IFDEF FPC}
  589. FQueueCondVar.SetEvent;
  590. {$ELSE}
  591. FQueueCondVar.ReleaseAll;
  592. {$ENDIF}
  593. end;
  594. function TThreadedQueueCS<T>.PopItem: T;
  595. var
  596. LQueueSize: Integer;
  597. begin
  598. PopItem(LQueueSize, Result);
  599. end;
  600. function TThreadedQueueCS<T>.PopItem(var AQueueSize: Integer; var AItem: T): TWaitResult;
  601. begin
  602. AItem := Default(T);
  603. FQueueLock.Enter;
  604. try
  605. Result := wrSignaled;
  606. while (Result = wrSignaled) and (FQueueSize = 0) and not FShutDown do
  607. begin
  608. {$IFDEF FPC}
  609. Result := FQueueCondVar.WaitFor(FPopTimeout);
  610. {$ELSE}
  611. Result := FQueueCondVar.WaitFor(FQueueLock, FPopTimeout);
  612. {$ENDIF}
  613. end;
  614. if (FShutDown and (FQueueSize = 0)) or (Result <> wrSignaled) then Exit;
  615. AItem := FQueue[FQueueOffset];
  616. FQueue[FQueueOffset] := Default(T);
  617. if FQueueSize = Length(FQueue) then
  618. begin
  619. {$IFDEF FPC}
  620. FQueueCondVar.SetEvent;
  621. {$ELSE}
  622. FQueueCondVar.ReleaseAll;
  623. {$ENDIF}
  624. end;
  625. Dec(FQueueSize);
  626. Inc(FQueueOffset);
  627. Inc(FTotalItemsPopped);
  628. if FQueueOffset = Length(FQueue) then FQueueOffset := 0;
  629. finally
  630. AQueueSize := FQueueSize;
  631. FQueueLock.Leave;
  632. end;
  633. end;
  634. function TThreadedQueueCS<T>.PopItem(var AItem: T): TWaitResult;
  635. var
  636. LQueueSize: Integer;
  637. begin
  638. Result := PopItem(LQueueSize, AItem);
  639. end;
  640. function TThreadedQueueCS<T>.PopItem(var AQueueSize: Integer): T;
  641. begin
  642. PopItem(AQueueSize, Result);
  643. end;
  644. function TThreadedQueueCS<T>.PushItem(const AItem: T): TWaitResult;
  645. var
  646. LQueueSize: Integer;
  647. begin
  648. Result := PushItem(AItem, LQueueSize);
  649. end;
  650. function TThreadedQueueCS<T>.PushItem(const AItem: T; var AQueueSize: Integer): TWaitResult;
  651. begin
  652. FQueueLock.Enter;
  653. try
  654. if FQueueSize >= High(FQueue) then
  655. begin
  656. if FQueueSize < 512 then Grow(FQueueSize * 2)
  657. else Grow(10);
  658. end;
  659. Result := wrSignaled;
  660. while (Result = wrSignaled) and (FQueueSize = Length(FQueue)) and not FShutDown do
  661. begin
  662. {$IFDEF FPC}
  663. Result := FQueueCondVar.WaitFor(FPushTimeout);
  664. {$ELSE}
  665. Result := FQueueCondVar.WaitFor(FQueueLock, FPushTimeout);
  666. {$ENDIF}
  667. end;
  668. if FShutDown or (Result <> wrSignaled) then Exit;
  669. if FQueueSize = 0 then
  670. begin
  671. {$IFDEF FPC}
  672. FQueueCondVar.SetEvent;
  673. {$ELSE}
  674. FQueueCondVar.ReleaseAll;
  675. {$ENDIF}
  676. end;
  677. FQueue[(FQueueOffset + FQueueSize) mod Length(FQueue)] := AItem;
  678. Inc(FQueueSize);
  679. Inc(FTotalItemsPushed);
  680. finally
  681. AQueueSize := FQueueSize;
  682. FQueueLock.Leave;
  683. end;
  684. end;
  685. procedure TThreadedQueueCS<T>.DoShutDown;
  686. begin
  687. FShutDown := True;
  688. {$IFDEF FPC}
  689. FQueueCondVar.SetEvent;
  690. {$ELSE}
  691. FQueueCondVar.ReleaseAll;
  692. {$ENDIF}
  693. end;
  694. { TThreadedQueueList<T> }
  695. constructor TThreadedQueueList<T>.Create(AQueueDepth: Integer = 10; PushTimeout: Cardinal = INFINITE; PopTimeout: Cardinal = INFINITE);
  696. begin
  697. inherited Create;
  698. fQueue := TQueue<T>.Create;
  699. fQueue.Capacity := AQueueDepth;
  700. fQueueSize := 0;
  701. fQueueLock := TCriticalSection.Create;
  702. {$IFDEF FPC}
  703. FQueueCondVar := TSimpleEvent.Create; //TEventObject.Create(nil, False, False, 'TQL');
  704. {$ELSE}
  705. fQueueCondVar := TConditionVariableCS.Create;
  706. {$ENDIF}
  707. fPushTimeout := PushTimeout;
  708. fPopTimeout := PopTimeout;
  709. end;
  710. destructor TThreadedQueueList<T>.Destroy;
  711. begin
  712. DoShutDown;
  713. fQueueLock.Free;
  714. fQueueCondVar.Free;
  715. fQueue.Free;
  716. inherited;
  717. end;
  718. procedure TThreadedQueueList<T>.Grow(ADelta: Integer);
  719. begin
  720. fQueueLock.Enter;
  721. try
  722. fQueue.Capacity := fQueue.Capacity + ADelta;
  723. finally
  724. fQueueLock.Leave;
  725. end;
  726. {$IFDEF FPC}
  727. FQueueCondVar.SetEvent;
  728. {$ELSE}
  729. FQueueCondVar.ReleaseAll;
  730. {$ENDIF}
  731. end;
  732. function TThreadedQueueList<T>.PopItem: T;
  733. var
  734. LQueueSize: Integer;
  735. begin
  736. PopItem(LQueueSize, Result);
  737. end;
  738. {$IFDEF FPC}
  739. function TThreadedQueueList<T>.PopItem(var AQueueSize: Integer; var AItem: T): TWaitResult;
  740. //var
  741. //crono : TChronometer;
  742. begin
  743. AItem := Default(T);
  744. //crono := TChronometer.Create(False);
  745. try
  746. Result := wrSignaled;
  747. //writeln('popitem');
  748. //crono.Start;
  749. while (Result = wrSignaled) and (fQueueSize = 0) and not fShutDown do
  750. begin
  751. //crono.Start;
  752. Result := FQueueCondVar.WaitFor(FPopTimeout);
  753. //crono.Stop;
  754. //writeln('in: ' + crono.ElapsedTime);
  755. //if result = twaitresult.wrError then result := twaitresult.wrError;
  756. end;
  757. //crono.Stop;
  758. //writeln('out: ' + crono.ElapsedTime);
  759. fQueueLock.Enter;
  760. try
  761. if (FShutDown and (fQueueSize = 0)) or (Result <> wrSignaled) then Exit;
  762. AItem := fQueue.Extract;
  763. Dec(FQueueSize);
  764. Inc(fTotalItemsPopped);
  765. finally
  766. fQueueLock.Leave;
  767. end;
  768. finally
  769. AQueueSize := fQueueSize;
  770. end;
  771. end;
  772. {$ELSE}
  773. function TThreadedQueueList<T>.PopItem(var AQueueSize: Integer; var AItem: T): TWaitResult;
  774. begin
  775. AItem := Default(T);
  776. fQueueLock.Enter;
  777. try
  778. Result := wrSignaled;
  779. while (Result = wrSignaled) and (fQueueSize = 0) and not fShutDown do
  780. begin
  781. Result := FQueueCondVar.WaitFor(FQueueLock, FPopTimeout);
  782. end;
  783. if (FShutDown and (fQueueSize = 0)) or (Result <> wrSignaled) then Exit;
  784. AItem := fQueue.Extract;
  785. if fQueueSize = fQueue.Count then
  786. begin
  787. FQueueCondVar.ReleaseAll;
  788. end;
  789. Dec(FQueueSize);
  790. Inc(fTotalItemsPopped);
  791. finally
  792. AQueueSize := fQueueSize;
  793. fQueueLock.Leave;
  794. end;
  795. end;
  796. {$ENDIF}
  797. function TThreadedQueueList<T>.PopItem(var AItem: T): TWaitResult;
  798. var
  799. LQueueSize: Integer;
  800. begin
  801. Result := PopItem(LQueueSize, AItem);
  802. end;
  803. function TThreadedQueueList<T>.PopItem(var AQueueSize: Integer): T;
  804. begin
  805. PopItem(AQueueSize, Result);
  806. end;
  807. function TThreadedQueueList<T>.PushItem(const AItem: T): TWaitResult;
  808. var
  809. LQueueSize: Integer;
  810. begin
  811. Result := PushItem(AItem, LQueueSize);
  812. end;
  813. {$IFDEF FPC}
  814. function TThreadedQueueList<T>.PushItem(const AItem: T; var AQueueSize: Integer): TWaitResult;
  815. begin
  816. FQueueLock.Enter;
  817. try
  818. if FQueueSize >= High(FQueue) then Grow(10);
  819. Result := wrSignaled;
  820. //while (Result = wrSignaled) and (fQueueSize = fQueue.Count) and not fShutDown do
  821. //begin
  822. // Result := fQueueCondVar.WaitFor(fQueueLock, fPushTimeout);
  823. //end;
  824. if fShutDown or (Result <> wrSignaled) then Exit;
  825. //if fQueueSize = 0 then
  826. //begin
  827. // FQueueCondVar.SetEvent;
  828. //end;
  829. fQueue.Enqueue(AItem);
  830. Inc(FQueueSize);
  831. Inc(fTotalItemsPushed);
  832. finally
  833. AQueueSize := fQueueSize;
  834. FQueueLock.Leave;
  835. //FQueueCondVar.SetEvent;
  836. end;
  837. end;
  838. {$ELSE}
  839. function TThreadedQueueList<T>.PushItem(const AItem: T; var AQueueSize: Integer): TWaitResult;
  840. begin
  841. FQueueLock.Enter;
  842. try
  843. Result := wrSignaled;
  844. //while (Result = wrSignaled) and (fQueueSize = fQueue.Count) and not fShutDown do
  845. //begin
  846. // Result := fQueueCondVar.WaitFor(fQueueLock, fPushTimeout);
  847. //end;
  848. if fShutDown or (Result <> wrSignaled) then Exit;
  849. if fQueueSize = 0 then FQueueCondVar.ReleaseAll;
  850. fQueue.Enqueue(AItem);
  851. Inc(FQueueSize);
  852. Inc(fTotalItemsPushed);
  853. finally
  854. AQueueSize := fQueueSize;
  855. FQueueLock.Leave;
  856. end;
  857. end;
  858. {$ENDIF}
  859. procedure TThreadedQueueList<T>.DoShutDown;
  860. begin
  861. fShutDown := True;
  862. {$IFDEF FPC}
  863. FQueueCondVar.SetEvent;
  864. {$ELSE}
  865. FQueueCondVar.ReleaseAll;
  866. {$ENDIF}
  867. end;
  868. {$IFNDEF FPC}
  869. { TThreadObjectList<T> }
  870. procedure TThreadObjectList<T>.Add(const Item: T);
  871. begin
  872. LockList;
  873. try
  874. if (Duplicates = dupAccept) or (fList.IndexOf(Item) = -1) then fList.Add(Item)
  875. else if Duplicates = dupError then raise EListError.CreateFmt(SDuplicateItem, [fList.ItemValue(Item)]);
  876. finally
  877. UnlockList;
  878. end;
  879. end;
  880. procedure TThreadObjectList<T>.Clear;
  881. begin
  882. LockList;
  883. try
  884. fList.Clear;
  885. finally
  886. UnlockList;
  887. end;
  888. end;
  889. constructor TThreadObjectList<T>.Create(OwnedObjects : Boolean);
  890. begin
  891. inherited Create;
  892. fLock := TObject.Create;
  893. fList := TObjectList<T>.Create;
  894. fDuplicates := dupIgnore;
  895. end;
  896. destructor TThreadObjectList<T>.Destroy;
  897. begin
  898. LockList;
  899. try
  900. fList.Free;
  901. inherited Destroy;
  902. finally
  903. UnlockList;
  904. fLock.Free;
  905. end;
  906. end;
  907. function TThreadObjectList<T>.GetItem(aIndex: Integer): T;
  908. begin
  909. LockList;
  910. try
  911. Result := fList[aIndex];
  912. finally
  913. UnlockList;
  914. end;
  915. end;
  916. function TThreadObjectList<T>.LockList: TObjectList<T>;
  917. begin
  918. System.TMonitor.Enter(fLock);
  919. Result := fList;
  920. end;
  921. procedure TThreadObjectList<T>.Remove(const Item: T);
  922. begin
  923. RemoveItem(Item, TDirection.FromBeginning);
  924. end;
  925. procedure TThreadObjectList<T>.RemoveItem(const Item: T; Direction: TDirection);
  926. begin
  927. LockList;
  928. try
  929. fList.RemoveItem(Item, Direction);
  930. finally
  931. UnlockList;
  932. end;
  933. end;
  934. procedure TThreadObjectList<T>.SetItem(aIndex: Integer; aValue: T);
  935. begin
  936. LockList;
  937. try
  938. fList[aIndex] := aValue;
  939. finally
  940. UnlockList;
  941. end;
  942. end;
  943. procedure TThreadObjectList<T>.UnlockList;
  944. begin
  945. System.TMonitor.Exit(fLock);
  946. end;
  947. {$ENDIF}
  948. { TAnonymousThread }
  949. constructor TAnonymousThread.Create(aProc : TProc; aSynchronize : Boolean);
  950. begin
  951. fThread := TAdvThread.Create(aProc,aSynchronize);
  952. end;
  953. class function TAnonymousThread.Execute(aProc: TProc): IAnonymousThread;
  954. begin
  955. Result := TAnonymousThread.Create(aProc,False);
  956. end;
  957. class function TAnonymousThread.Execute_Sync(aProc: TProc): IAnonymousThread;
  958. begin
  959. Result := TAnonymousThread.Create(aProc,True);
  960. end;
  961. function TAnonymousThread.OnException(aProc: TAnonExceptionProc): IAnonymousThread;
  962. begin
  963. Result := Self;
  964. fThread.OnException(aProc);
  965. end;
  966. function TAnonymousThread.OnTerminate(aProc: TProc): IAnonymousThread;
  967. begin
  968. Result := Self;
  969. fThread.OnTerminate(aProc,False);
  970. end;
  971. function TAnonymousThread.OnTerminate_Sync(aProc: TProc): IAnonymousThread;
  972. begin
  973. Result := Self;
  974. fThread.OnTerminate(aProc,True);
  975. end;
  976. procedure TAnonymousThread.Start;
  977. begin
  978. fThread.Start;
  979. end;
  980. { TTask }
  981. constructor TTask.Create(aParamArray : array of const; aOwnedParams : Boolean; aTaskProc : TTaskProc);
  982. var
  983. i : Integer;
  984. begin
  985. fTaskStatus := TWorkTaskStatus.wtsPending;
  986. fCustomFaultPolicy := False;
  987. fNumRetries := 0;
  988. fExecuteWithSync := False;
  989. fTerminateWithSync := False;
  990. fExceptionWithSync := False;
  991. fFaultControl := TFaultControl.Create;
  992. fFaultControl.OnRetry := DoRetry;
  993. fOwnedParams := aOwnedParams;
  994. fParamList := TParamList.Create(True);
  995. for i := Low(aParamArray) to High(aParamArray) do
  996. begin
  997. fParamList.Add(TParamValue.Create(i.ToString,aParamArray[i],aOwnedParams));
  998. {$IFDEF FPC}
  999. fParamList[i].Value._AddRef;
  1000. {$ENDIF}
  1001. end;
  1002. fExecuteProc := aTaskProc;
  1003. fEnabled := False;
  1004. end;
  1005. destructor TTask.Destroy;
  1006. var
  1007. i : Integer;
  1008. begin
  1009. fFaultControl.Free;
  1010. //free passed params
  1011. fParamList.Free;
  1012. if (not fResult.IsNullOrEmpty) and (fResult.IsObject) then fResult.AsObject.Free;
  1013. inherited;
  1014. end;
  1015. procedure TTask.DoException(aException : Exception);
  1016. begin
  1017. fTaskStatus := TWorkTaskStatus.wtsException;
  1018. if Assigned(fExceptProc) then fExceptProc(Self,aException)
  1019. else raise aException;
  1020. end;
  1021. procedure TTask.DoExecute;
  1022. begin
  1023. fTaskStatus := TWorkTaskStatus.wtsRunning;
  1024. DoInitialize;
  1025. repeat
  1026. try
  1027. if Assigned(fExecuteProc) then fExecuteProc(Self);
  1028. fTaskStatus := TWorkTaskStatus.wtsDone;
  1029. fFaultControl.SuccessExecution;
  1030. except
  1031. on E : Exception do
  1032. begin
  1033. fTaskStatus := TWorkTaskStatus.wtsException;
  1034. {$IFNDEF FPC}
  1035. fFaultControl.FailedExecution(AcquireExceptionObject as Exception);
  1036. {$ELSE}
  1037. fFaultControl.FailedExecution(Exception(AcquireExceptionObject));
  1038. {$ENDIF}
  1039. end;
  1040. end;
  1041. until not fFaultControl.NeedToRetry;
  1042. end;
  1043. procedure TTask.DoInitialize;
  1044. begin
  1045. try
  1046. fFaultControl.Reset;
  1047. if Assigned(fInitializeProc) then fInitializeProc(Self);
  1048. except
  1049. on E : Exception do
  1050. begin
  1051. raise ETaskInitializationError.CreateFmt('Task initialization failed: %s',[e.Message]);
  1052. end;
  1053. end;
  1054. end;
  1055. function TTask.Done: Boolean;
  1056. begin
  1057. Result := not fFaultControl.TaskFailed;
  1058. end;
  1059. function TTask.Failed: Boolean;
  1060. begin
  1061. Result := fFaultControl.TaskFailed;
  1062. end;
  1063. function TTask.CircuitBreaked: Boolean;
  1064. begin
  1065. Result := fFaultControl.CircuitBreaked;
  1066. end;
  1067. function TTask.LastException: Exception;
  1068. begin
  1069. Result := fFaultControl.LastException;
  1070. end;
  1071. function TTask.MaxRetries: Integer;
  1072. begin
  1073. Result := fFaultControl.MaxRetries;
  1074. end;
  1075. function TTask.NumRetries: Integer;
  1076. begin
  1077. Result := fFaultControl.NumRetries;
  1078. end;
  1079. procedure TTask.DoRetry(aRaisedException: Exception; var vStopRetries: Boolean);
  1080. begin
  1081. vStopRetries := False;
  1082. if Assigned(fRetryProc) then fRetryProc(Self,aRaisedException,vStopRetries);
  1083. end;
  1084. procedure TTask.DoTerminate;
  1085. begin
  1086. if Assigned(fTerminateProc) then fTerminateProc(Self);
  1087. end;
  1088. function TTask.GetIdTask: Int64;
  1089. begin
  1090. Result := fIdTask;
  1091. end;
  1092. procedure TTask.SetFaultPolicy(aFaultPolicy: TFaultPolicy);
  1093. begin
  1094. {$IFDEF FPC}
  1095. if not Assigned(fFaultControl) then fFaultControl := TFaultControl.Create;
  1096. {$ENDIF}
  1097. fFaultControl.MaxRetries := aFaultPolicy.MaxRetries;
  1098. fFaultControl.WaitTimeBetweenRetriesMS := aFaultPolicy.WaitTimeBetweenRetries;
  1099. fFaultControl.WaitTimeMultiplierFactor := aFaultPolicy.WaitTimeMultiplierFactor;
  1100. end;
  1101. procedure TTask.SetIdTask(Value : Int64);
  1102. begin
  1103. fIdTask := Value;
  1104. end;
  1105. function TTask.GetNumWorker: Integer;
  1106. begin
  1107. Result := fNumWorker;
  1108. end;
  1109. function TTask.GetParam(aIndex: Integer): TFlexValue;
  1110. begin
  1111. Result := fParamList[aIndex].Value;
  1112. end;
  1113. function TTask.GetParam(const aName: string): TFlexValue;
  1114. var
  1115. paramvalue : TParamValue;
  1116. begin
  1117. for paramvalue in fParamList do
  1118. begin
  1119. if CompareText(paramvalue.Name,aName) = 0 then
  1120. begin
  1121. Exit(paramvalue.Value)
  1122. end;
  1123. end;
  1124. //if not exists
  1125. raise ETaskParamError.CreateFmt('Task param "%s" not found!',[aName]);
  1126. end;
  1127. function TTask.GetParam2(aIndex: Integer): PFlexValue;
  1128. begin
  1129. Result := @fParamList[aIndex].Value;
  1130. end;
  1131. function TTask.GetResult: TFlexValue;
  1132. begin
  1133. Result := fResult;
  1134. end;
  1135. function TTask.IsEnabled: Boolean;
  1136. begin
  1137. Result := fEnabled;
  1138. end;
  1139. procedure TTask.SetNumWorker(Value: Integer);
  1140. begin
  1141. fTaskStatus := TWorkTaskStatus.wtsAssigned;
  1142. fNumWorker := Value;
  1143. end;
  1144. procedure TTask.SetParam(aIndex: Integer; Value: TFlexValue);
  1145. begin
  1146. if aIndex > fParamList.Count then raise ETaskParamError.CreateFmt('Task parameter index(%d) not found',[aIndex]);
  1147. fParamList[aIndex].Value := Value;
  1148. end;
  1149. procedure TTask.SetParam(const aName: string; Value: TFlexValue; aOwned: Boolean);
  1150. var
  1151. paramvalue : TParamValue;
  1152. begin
  1153. //check if already exists parameter
  1154. for paramvalue in fParamList do
  1155. begin
  1156. if CompareText(paramvalue.Name,aName) = 0 then
  1157. begin
  1158. paramvalue.Value := Value;
  1159. Exit;
  1160. end;
  1161. end;
  1162. //if not exists, create one
  1163. fParamList.Add(TParamValue.Create(aName,Value,aOwned));
  1164. end;
  1165. procedure TTask.SetParam(const aName: string; Value: TFlexValue);
  1166. begin
  1167. SetParam(aName,Value,False);
  1168. end;
  1169. procedure TTask.SetRetryPolicy(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer; aWaitTimeMultiplierFactor: Double);
  1170. begin
  1171. fFaultControl.MaxRetries := aMaxRetries;
  1172. fFaultControl.WaitTimeBetweenRetriesMS := aWaitTimeBetweenRetriesMS;
  1173. fFaultControl.WaitTimeMultiplierFactor := aWaitTimeMultiplierFactor;
  1174. fCustomFaultPolicy := True;
  1175. end;
  1176. procedure TTask.SetResult(aValue: TFlexValue);
  1177. begin
  1178. fResult := aValue;
  1179. end;
  1180. procedure TTask.SetRetryPolicy(aWaitTimeMSArray: TArray<Integer>);
  1181. begin
  1182. fFaultControl.MaxRetries := High(aWaitTimeMSArray) + 1;
  1183. fFaultControl.WaitTimeBetweenRetriesMS := 0;
  1184. fFaultControl.WaitTimeMultiplierFactor := 0;
  1185. fFaultControl.WaitTimeMSArray := aWaitTimeMSArray;
  1186. fCustomFaultPolicy := True;
  1187. end;
  1188. function TTask.TaskStatus: TWorkTaskStatus;
  1189. begin
  1190. Result := fTaskStatus;
  1191. end;
  1192. { TWorkTask }
  1193. function TWorkTask.OnException(aTaskProc : TTaskExceptionProc) : IWorkTask;
  1194. begin
  1195. fExceptProc := aTaskProc;
  1196. Result := Self;
  1197. end;
  1198. function TWorkTask.OnInitialize(aTaskProc: TTaskProc): IWorkTask;
  1199. begin
  1200. fInitializeProc := aTaskProc;
  1201. Result := Self;
  1202. end;
  1203. function TWorkTask.OnRetry(aTaskProc: TTaskRetryProc): IWorkTask;
  1204. begin
  1205. fRetryProc := aTaskProc;
  1206. Result := Self;
  1207. end;
  1208. function TWorkTask.OnTerminated(aTaskProc: TTaskProc): IWorkTask;
  1209. begin
  1210. fTerminateProc := aTaskProc;
  1211. Result := Self;
  1212. end;
  1213. procedure TWorkTask.Run;
  1214. begin
  1215. fEnabled := True;
  1216. end;
  1217. function TWorkTask.SetParameter(const aName: string; aValue: TFlexValue): IWorkTask;
  1218. begin
  1219. Result := Self;
  1220. SetParam(aName,aValue);
  1221. end;
  1222. function TWorkTask.SetParameter(const aName: string; aValue: TFlexValue; aOwned: Boolean): IWorkTask;
  1223. begin
  1224. Result := Self;
  1225. SetParam(aName,aValue,aOwned);
  1226. end;
  1227. function TWorkTask.Retry(aMaxRetries: Integer): IWorkTask;
  1228. begin
  1229. Result := Self;
  1230. SetRetryPolicy(aMaxRetries,0,0);
  1231. end;
  1232. function TWorkTask.RetryForever: IWorkTask;
  1233. begin
  1234. Result := Self;
  1235. SetRetryPolicy(-1,0,0);
  1236. end;
  1237. function TWorkTask.WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS: Integer): IWorkTask;
  1238. begin
  1239. Result := Self;
  1240. SetRetryPolicy(aMaxRetries,aWaitTimeBetweenRetriesMS,0);
  1241. end;
  1242. function TWorkTask.WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS: Integer; aWaitTimeMultiplierFactor : Double): IWorkTask;
  1243. begin
  1244. Result := Self;
  1245. SetRetryPolicy(aMaxRetries,aWaitTimeBetweenRetriesMS,aWaitTimeMultiplierFactor);
  1246. end;
  1247. function TWorkTask.WaitAndRetry(aWaitTimeArray: TArray<Integer>): IWorkTask;
  1248. begin
  1249. Result := Self;
  1250. SetRetryPolicy(aWaitTimeArray);
  1251. end;
  1252. function TWorkTask.WaitAndRetryForever(aWaitTimeBetweenRetriesMS: Integer): IWorkTask;
  1253. begin
  1254. Result := Self;
  1255. SetRetryPolicy(-1,aWaitTimeBetweenRetriesMS,0);
  1256. end;
  1257. function TWorkTask.WaitAndRetryForever(aMaxRetries, aWaitTimeBetweenRetriesMS: Integer; aWaitTimeMultiplierFactor: Double): IWorkTask;
  1258. begin
  1259. Result := Self;
  1260. SetRetryPolicy(-1,aWaitTimeBetweenRetriesMS,aWaitTimeMultiplierFactor);
  1261. end;
  1262. { TBackgroundTasks }
  1263. procedure TBackgroundTasks.CancelAll;
  1264. begin
  1265. fTaskQueue.Clear;
  1266. end;
  1267. constructor TBackgroundTasks.Create(aConcurrentWorkers : Integer; aInitialQueueSize : Integer = 100);
  1268. begin
  1269. fMaxQueue := 0;
  1270. fConcurrentWorkers := aConcurrentWorkers;
  1271. fInsertTimeout := INFINITE;
  1272. fExtractTimeout := 5000;
  1273. fNumPushedTasks := 0;
  1274. fTaskQueue := TThreadedQueueCS<IWorkTask>.Create(aInitialQueueSize,fInsertTimeout,fExtractTimeout);
  1275. end;
  1276. destructor TBackgroundTasks.Destroy;
  1277. begin
  1278. CancelAll;
  1279. fTaskQueue.DoShutDown;
  1280. //while fTaskQueue.QueueSize > 0 do Sleep(0);
  1281. if Assigned(fWorkerPool) then fWorkerPool.Free;
  1282. if Assigned(fTaskQueue) then fTaskQueue.Free;
  1283. inherited;
  1284. end;
  1285. function TBackgroundTasks.GetTaskQueue: Cardinal;
  1286. begin
  1287. Result := fTaskQueue.QueueSize;
  1288. end;
  1289. function TBackgroundTasks.AddTask(aTaskProc : TTaskProc) : IWorkTask;
  1290. begin
  1291. Result := AddTask([],False,aTaskProc);
  1292. end;
  1293. function TBackgroundTasks.AddTask(aParamArray : array of const; aOwnedParams : Boolean; aTaskProc : TTaskProc) : IWorkTask;
  1294. var
  1295. worktask : IWorkTask;
  1296. begin
  1297. if (fMaxQueue > 0) and (fTaskQueue.QueueSize >= fMaxQueue) then raise ETaskAddError.Create('Max queue reached: Task cannot be added');
  1298. worktask := TWorkTask.Create(aParamArray,aOwnedParams,aTaskProc);
  1299. Inc(fNumPushedTasks);
  1300. worktask.SetIdTask(fNumPushedTasks);
  1301. if fTaskQueue.PushItem(worktask) = TWaitResult.wrSignaled then
  1302. begin
  1303. Result := worktask;
  1304. end;
  1305. end;
  1306. function TBackgroundTasks.AddTask_Sync(aParamArray: array of const; aOwnedParams: Boolean; aTaskProc: TTaskProc): IWorkTask;
  1307. begin
  1308. Result := AddTask(aParamArray,aOwnedParams,aTaskProc);
  1309. TTask(Result).ExecuteWithSync := True;
  1310. end;
  1311. function TBackgroundTasks.AddTask_Sync(aTaskProc: TTaskProc): IWorkTask;
  1312. begin
  1313. Result := AddTask_Sync([],False,aTaskProc);
  1314. end;
  1315. procedure TBackgroundTasks.Start;
  1316. var
  1317. i : Integer;
  1318. worker : TWorker;
  1319. begin
  1320. //create workers
  1321. if fWorkerPool <> nil then fWorkerPool.Free;
  1322. fWorkerPool := TWorkerPool.Create(True);
  1323. for i := 1 to fConcurrentWorkers do
  1324. begin
  1325. worker := TQueueWorker.Create(i,fTaskQueue);
  1326. fWorkerPool.Add(worker);
  1327. worker.Start;
  1328. end;
  1329. end;
  1330. { TWorker }
  1331. constructor TWorker.Create;
  1332. begin
  1333. inherited Create(True);
  1334. fDefaultFaultPolicy := TFaultPolicy.Create;
  1335. fStatus := TWorkerStatus.wsSuspended;
  1336. FreeOnTerminate := False;
  1337. end;
  1338. destructor TWorker.Destroy;
  1339. begin
  1340. if Assigned(fDefaultFaultPolicy) then fDefaultFaultPolicy.Free;
  1341. inherited;
  1342. end;
  1343. procedure TWorker.SetFaultPolicy(aTask: TTask);
  1344. begin
  1345. if not aTask.CustomFaultPolicy then aTask.SetFaultPolicy(fDefaultFaultPolicy);
  1346. end;
  1347. procedure TWorker.Execute;
  1348. begin
  1349. end;
  1350. procedure TWorker.ExecuteTask;
  1351. begin
  1352. fCurrentTask.DoExecute;
  1353. end;
  1354. procedure TWorker.TerminateTask;
  1355. begin
  1356. fCurrentTask.DoTerminate;
  1357. end;
  1358. { TSimpleWorker }
  1359. constructor TSimpleWorker.Create(aTask : ITask);
  1360. begin
  1361. inherited Create;
  1362. fCurrentTask := aTask;
  1363. FreeOnTerminate := True;
  1364. end;
  1365. procedure TSimpleWorker.Execute;
  1366. begin
  1367. fStatus := TWorkerStatus.wsIdle;
  1368. while not Terminated do
  1369. begin
  1370. if (fCurrentTask <> nil) and (fCurrentTask.IsEnabled) then
  1371. try
  1372. fStatus := TWorkerStatus.wsWorking;
  1373. try
  1374. if TTask(fCurrentTask).ExecuteWithSync then Synchronize(ExecuteTask)
  1375. else fCurrentTask.DoExecute;
  1376. except
  1377. on E : Exception do
  1378. begin
  1379. if fCurrentTask <> nil then fCurrentTask.DoException(E)
  1380. else raise ETaskExecutionError.Create(e.Message);
  1381. end;
  1382. end;
  1383. finally
  1384. if TTask(fCurrentTask).TerminateWithSync then Synchronize(TerminateTask)
  1385. else fCurrentTask.DoTerminate;
  1386. fStatus := TWorkerStatus.wsIdle;
  1387. Terminate;
  1388. end;
  1389. end;
  1390. fStatus := TWorkerStatus.wsSuspended
  1391. end;
  1392. { TQueueWorker }
  1393. constructor TQueueWorker.Create(aNumWorker: Integer; aTaskQueue: TTaskQueue);
  1394. begin
  1395. inherited Create;
  1396. fNumWorker := aNumWorker;
  1397. fTaskQueue := aTaskQueue;
  1398. end;
  1399. procedure TQueueWorker.Execute;
  1400. begin
  1401. fStatus := TWorkerStatus.wsIdle;
  1402. while not Terminated do
  1403. begin
  1404. fCurrentTask := fTaskQueue.PopItem;
  1405. if fCurrentTask <> nil then
  1406. try
  1407. fStatus := TWorkerStatus.wsWorking;
  1408. try
  1409. fCurrentIdTask := fCurrentTask.GetIdTask;
  1410. SetFaultPolicy(TTask(fCurrentTask));
  1411. if TTask(fCurrentTask).ExecuteWithSync then Synchronize(ExecuteTask)
  1412. else fCurrentTask.DoExecute;
  1413. except
  1414. on E : Exception do
  1415. begin
  1416. if fCurrentTask <> nil then fCurrentTask.DoException(E)
  1417. else raise ETaskExecutionError.Create(e.Message);
  1418. end;
  1419. end;
  1420. finally
  1421. if TTask(fCurrentTask).TerminateWithSync then Synchronize(TerminateTask)
  1422. else fCurrentTask.DoTerminate;
  1423. fStatus := TWorkerStatus.wsIdle;
  1424. end;
  1425. end;
  1426. fStatus := TWorkerStatus.wsSuspended
  1427. end;
  1428. { TScheduledWorker }
  1429. constructor TScheduledWorker.Create(aNumWorker : Integer; aScheduledTask: IScheduledTask);
  1430. begin
  1431. inherited Create;
  1432. {$IFNDEF DELPHILINUX}
  1433. NameThreadForDebugging(aScheduledTask.Name,aScheduledTask.IdTask);
  1434. {$ENDIF}
  1435. FreeOnTerminate := True;
  1436. fCurrentTask := aScheduledTask;
  1437. end;
  1438. procedure TScheduledWorker.Execute;
  1439. begin
  1440. fStatus := TWorkerStatus.wsIdle;
  1441. if Assigned(fCurrentTask) then
  1442. begin
  1443. try
  1444. fStatus := TWorkerStatus.wsWorking;
  1445. try
  1446. SetFaultPolicy(TTask(fCurrentTask));
  1447. if TTask(fCurrentTask).ExecuteWithSync then Synchronize(ExecuteTask)
  1448. else fCurrentTask.DoExecute;
  1449. fStatus := TWorkerStatus.wsIdle;
  1450. except
  1451. on E : Exception do
  1452. begin
  1453. if fCurrentTask <> nil then fCurrentTask.DoException(E)
  1454. else raise ETaskExecutionError.Create(e.Message);
  1455. end;
  1456. end;
  1457. finally
  1458. if TTask(fCurrentTask).TerminateWithSync then Synchronize(TerminateTask)
  1459. else fCurrentTask.DoTerminate;
  1460. //check if expired
  1461. if (fCurrentTask as IScheduledTask).IsFinished then
  1462. begin
  1463. if TScheduledTask(fCurrentTask).ExpireWithSync then Synchronize(ExpireTask)
  1464. else (fCurrentTask as IScheduledTask).DoExpire;
  1465. end;
  1466. end;
  1467. end;
  1468. fCurrentTask := nil;
  1469. fStatus := TWorkerStatus.wsSuspended;
  1470. end;
  1471. procedure TScheduledWorker.ExpireTask;
  1472. begin
  1473. (fCurrentTask as IScheduledTask).DoExpire;
  1474. end;
  1475. { TScheduledTasks }
  1476. function TScheduledTasks.AddTask(const aTaskName : string; aTaskProc : TTaskProc) : IScheduledTask;
  1477. begin
  1478. Result := AddTask(aTaskName,[],False,aTaskProc);
  1479. end;
  1480. function TScheduledTasks.AddTask(const aTaskName : string; aParamArray: array of const; aOwnedParams : Boolean; aTaskProc: TTaskProc): IScheduledTask;
  1481. var
  1482. scheduletask : TScheduledTask;
  1483. begin
  1484. scheduletask := TScheduledTask.Create(aParamArray,aOwnedParams,aTaskProc);
  1485. scheduletask.Name := aTaskName;
  1486. Inc(fNumPushedTasks);
  1487. scheduletask.SetIdTask(fNumPushedTasks);
  1488. fTaskList.Add(scheduletask);
  1489. Result := scheduletask;
  1490. end;
  1491. function TScheduledTasks.AddTask_Sync(const aTaskName: string; aParamArray: array of const; aOwnedParams: Boolean; aTaskProc: TTaskProc): IScheduledTask;
  1492. begin
  1493. Result := AddTask(aTaskName,aParamArray,aOwnedParams,aTaskProc);
  1494. TTask(Result).ExecuteWithSync := True;
  1495. end;
  1496. function TScheduledTasks.AddTask_Sync(const aTaskName: string; aTaskProc: TTaskProc): IScheduledTask;
  1497. begin
  1498. Result := AddTask_Sync(aTaskName,[],False,aTaskProc);
  1499. end;
  1500. constructor TScheduledTasks.Create;
  1501. begin
  1502. fNumPushedTasks := 0;
  1503. fIsStarted := False;
  1504. fFaultPolicy := TFaultPolicy.Create;
  1505. fTaskList := TScheduledTaskList.Create;
  1506. end;
  1507. destructor TScheduledTasks.Destroy;
  1508. begin
  1509. if Assigned(fScheduler) then
  1510. begin
  1511. fScheduler.Terminate;
  1512. fScheduler.WaitFor;
  1513. fScheduler.Free;
  1514. end;
  1515. if Assigned(fTaskList) then fTaskList.Free;
  1516. if Assigned(fFaultPolicy) then fFaultPolicy.Free;
  1517. inherited;
  1518. end;
  1519. function TScheduledTasks.GetTask(aIdTask: Int64): IScheduledTask;
  1520. begin
  1521. Result := fScheduler.Get(aIdTask);
  1522. end;
  1523. function TScheduledTasks.GetTask(const aTaskName: string): IScheduledTask;
  1524. begin
  1525. if not Assigned(fScheduler) then raise ETaskSchedulerError.Create('Scheduler must be started to get a task!');
  1526. Result := fScheduler.Get(aTaskName);
  1527. end;
  1528. procedure TScheduledTasks.Start;
  1529. begin
  1530. if fIsStarted then Exit;
  1531. if not Assigned(fScheduler) then
  1532. begin
  1533. fScheduler := TScheduler.Create(fTaskList);
  1534. fScheduler.RemoveTaskAfterExpiration := fRemoveTaskAfterExpiration;
  1535. end;
  1536. fScheduler.Start;
  1537. fIsStarted := True;
  1538. end;
  1539. procedure TScheduledTasks.Stop;
  1540. begin
  1541. if Assigned(fScheduler) then fScheduler.Terminate;
  1542. fIsStarted := False;
  1543. end;
  1544. { TScheduledTask }
  1545. function TScheduledTask.SetParameter(const aName: string; aValue: TFlexValue): IScheduledTask;
  1546. begin
  1547. Result := Self;
  1548. SetParam(aName,aValue);
  1549. end;
  1550. function TScheduledTask.SetParameter(const aName: string; aValue: TFlexValue; aOwned: Boolean): IScheduledTask;
  1551. begin
  1552. Result := Self;
  1553. SetParam(aName,aValue);
  1554. end;
  1555. function TScheduledTask.StartAt(aStartDate: TDateTime) : IScheduledTask;
  1556. begin
  1557. Result := Self;
  1558. ClearSchedule;
  1559. fScheduleMode := TScheduleMode.smRunOnce;
  1560. fStartDate := aStartDate;
  1561. fNextExecution := aStartDate;
  1562. end;
  1563. function TScheduledTask.StartInMinutes(aMinutes: Word): IScheduledTask;
  1564. begin
  1565. Result := Self;
  1566. ClearSchedule;
  1567. fScheduleMode := TScheduleMode.smRunOnce;
  1568. fStartDate := IncMinute(Now(),aMinutes);
  1569. fNextExecution := fStartDate;
  1570. end;
  1571. function TScheduledTask.StartInSeconds(aSeconds: Word): IScheduledTask;
  1572. begin
  1573. Result := Self;
  1574. ClearSchedule;
  1575. fScheduleMode := TScheduleMode.smRunOnce;
  1576. fStartDate := IncSecond(Now(),aSeconds);
  1577. fNextExecution := fStartDate;
  1578. end;
  1579. function TScheduledTask.StartNow: IScheduledTask;
  1580. begin
  1581. Result := Self;
  1582. ClearSchedule;
  1583. fScheduleMode := TScheduleMode.smRunOnce;
  1584. fStartDate := Now();
  1585. fNextExecution := fStartDate;
  1586. end;
  1587. function TScheduledTask.StartOnDayChange: IScheduledTask;
  1588. begin
  1589. Result := Self;
  1590. ClearSchedule;
  1591. fScheduleMode := TScheduleMode.smRunOnce;
  1592. fStartDate := ChangeTimeOfADay(Tomorrow(),0,0,0);
  1593. fNextExecution := fStartDate;
  1594. end;
  1595. function TScheduledTask.StartTodayAt(aHour, aMinute: Word; aSecond : Word = 0): IScheduledTask;
  1596. begin
  1597. Result := Self;
  1598. ClearSchedule;
  1599. fScheduleMode := TScheduleMode.smRunOnce;
  1600. fStartDate := ChangeDateOfADay(Now(),aHour,aMinute,aSecond);
  1601. fNextExecution := fStartDate;
  1602. end;
  1603. function TScheduledTask.StartTomorrowAt(aHour, aMinute: Word; aSecond : Word = 0): IScheduledTask;
  1604. begin
  1605. Result := Self;
  1606. ClearSchedule;
  1607. fScheduleMode := TScheduleMode.smRunOnce;
  1608. fStartDate := ChangeTimeOfADay(Tomorrow(),aHour,aMinute,aSecond);
  1609. fNextExecution := fStartDate;
  1610. end;
  1611. function TScheduledTask.Retry(aMaxRetries: Integer): IScheduledTask;
  1612. begin
  1613. Result := Self;
  1614. SetRetryPolicy(aMaxRetries,0,0);
  1615. end;
  1616. function TScheduledTask.RetryForever: IScheduledTask;
  1617. begin
  1618. Result := Self;
  1619. SetRetryPolicy(-1,0,0);
  1620. end;
  1621. function TScheduledTask.WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS: Integer): IScheduledTask;
  1622. begin
  1623. Result := Self;
  1624. SetRetryPolicy(aMaxRetries,aWaitTimeBetweenRetriesMS,0);
  1625. end;
  1626. function TScheduledTask.WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS: Integer; aWaitTimeMultiplierFactor : Double): IScheduledTask;
  1627. begin
  1628. Result := Self;
  1629. SetRetryPolicy(aMaxRetries,aWaitTimeBetweenRetriesMS,aWaitTimeMultiplierFactor);
  1630. end;
  1631. function TScheduledTask.WaitAndRetry(aWaitTimeArray: TArray<Integer>): IScheduledTask;
  1632. begin
  1633. Result := Self;
  1634. SetRetryPolicy(aWaitTimeArray);
  1635. end;
  1636. function TScheduledTask.WaitAndRetryForever(aWaitTimeBetweenRetriesMS: Integer): IScheduledTask;
  1637. begin
  1638. Result := Self;
  1639. SetRetryPolicy(-1,aWaitTimeBetweenRetriesMS,0);
  1640. end;
  1641. function TScheduledTask.WaitAndRetryForever(aMaxRetries, aWaitTimeBetweenRetriesMS: Integer; aWaitTimeMultiplierFactor: Double): IScheduledTask;
  1642. begin
  1643. Result := Self;
  1644. SetRetryPolicy(-1,aWaitTimeBetweenRetriesMS,aWaitTimeMultiplierFactor);
  1645. end;
  1646. procedure TScheduledTask.RepeatEvery(aInterval: Integer; aTimeMeasure: TTimeMeasure);
  1647. begin
  1648. if fStartDate = 0.0 then ClearSchedule;
  1649. fScheduleMode := TScheduleMode.smRepeatMode;
  1650. fTimeMeasure := aTimeMeasure;
  1651. fTimeInterval := aInterval;
  1652. if fStartDate < Now() then fStartDate := Now();
  1653. fNextExecution := fStartDate;
  1654. fEnabled := True;
  1655. end;
  1656. procedure TScheduledTask.RepeatEvery(aInterval : Integer; aTimeMeasure : TTimeMeasure; aEndTime : TDateTime);
  1657. begin
  1658. if fStartDate = 0.0 then ClearSchedule;
  1659. fScheduleMode := TScheduleMode.smRepeatMode;
  1660. fTimeMeasure := aTimeMeasure;
  1661. fTimeInterval := aInterval;
  1662. if fStartDate < Now() then fStartDate := Now();
  1663. fExpirationDate := aEndTime;
  1664. fNextExecution := fStartDate;
  1665. fEnabled := True;
  1666. end;
  1667. procedure TScheduledTask.RepeatEveryDay;
  1668. begin
  1669. RepeatEvery(1,tmDays);
  1670. end;
  1671. procedure TScheduledTask.RepeatEveryWeek;
  1672. begin
  1673. RepeatEvery(7,tmDays);
  1674. end;
  1675. procedure TScheduledTask.RepeatEvery(aInterval : Integer; aTimeMeasure : TTimeMeasure; aRepeatTimes : Integer);
  1676. begin
  1677. if fStartDate = 0.0 then ClearSchedule;
  1678. fScheduleMode := TScheduleMode.smRepeatMode;
  1679. fTimeMeasure := aTimeMeasure;
  1680. fTimeInterval := aInterval;
  1681. if fStartDate < Now() then fStartDate := Now();
  1682. fExpirationTimes := aRepeatTimes;
  1683. fNextExecution := fStartDate;
  1684. fEnabled := True;
  1685. end;
  1686. procedure TScheduledTask.RunOnce;
  1687. begin
  1688. fScheduleMode := TScheduleMode.smRunOnce;
  1689. if fStartDate < Now() then fStartDate := Now();
  1690. fNextExecution := fStartDate;
  1691. fEnabled := True;
  1692. end;
  1693. procedure TScheduledTask.Cancel;
  1694. begin
  1695. fFinished := True;
  1696. end;
  1697. function TScheduledTask.CheckSchedule: Boolean;
  1698. begin
  1699. Result := False;
  1700. if fTaskStatus = TWorkTaskStatus.wtsRunning then Exit;
  1701. if fScheduleMode = TScheduleMode.smRunOnce then
  1702. begin
  1703. //if start date reached
  1704. if (fExecutionTimes = 0) and (Now() >= fNextExecution) then
  1705. begin
  1706. fLastExecution := Now();
  1707. Inc(fExecutionTimes);
  1708. fFinished := True;
  1709. Result := True;
  1710. end;
  1711. end
  1712. else
  1713. begin
  1714. //if next execution reached
  1715. if Now() >= fNextExecution then
  1716. begin
  1717. //check expiration limits
  1718. if ((fExpirationTimes > 0) and (fExecutionTimes > fExpirationTimes)) or
  1719. ((fExpirationDate > 0.0) and (fNextExecution >= fExpirationDate)) then
  1720. begin
  1721. fFinished := True;
  1722. Exit;
  1723. end;
  1724. //calculate next execution
  1725. case fTimeMeasure of
  1726. tmDays : fNextExecution := IncDay(fNextExecution,fTimeInterval);
  1727. tmHours : fNextExecution := IncHour(fNextExecution,fTimeInterval);
  1728. tmMinutes : fNextExecution := IncMinute(fNextExecution,fTimeInterval);
  1729. tmSeconds : fNextExecution := IncSecond(fNextExecution,fTimeInterval);
  1730. tmMilliseconds : fNextExecution := IncMilliSecond(fNextExecution, fTimeInterval);
  1731. end;
  1732. if Now() > fNextExecution then Result := False //avoid execution if system time was altered
  1733. else
  1734. begin
  1735. fLastExecution := Now();
  1736. Inc(fExecutionTimes);
  1737. Result := True;
  1738. end;
  1739. end;
  1740. end;
  1741. end;
  1742. procedure TScheduledTask.ClearSchedule;
  1743. begin
  1744. inherited;
  1745. fFinished := False;
  1746. fStartDate := 0.0;
  1747. fLastExecution := 0.0;
  1748. fNextExecution := 0.0;
  1749. fExpirationDate := 0.0;
  1750. fScheduleMode := TScheduleMode.smRunOnce;
  1751. fTimeMeasure := TTimeMeasure.tmSeconds;
  1752. fTimeInterval := 0;
  1753. end;
  1754. procedure TScheduledTask.DoExpire;
  1755. begin
  1756. if Assigned(fExpiredProc) then fExpiredProc(Self);
  1757. fEnabled := False;
  1758. end;
  1759. function TScheduledTask.GetCurrentSchedule: TPair<TTimeMeasure, Integer>;
  1760. begin
  1761. Result := TPair<TTimeMeasure, Integer>.Create(fTimeMeasure, fTimeInterval);
  1762. end;
  1763. function TScheduledTask.GetTaskName: string;
  1764. begin
  1765. Result := fName;
  1766. end;
  1767. function TScheduledTask.IsFinished: Boolean;
  1768. begin
  1769. Result := fFinished;
  1770. end;
  1771. function TScheduledTask.OnException(aTaskProc: TTaskExceptionProc): IScheduledTask;
  1772. begin
  1773. fExceptProc := aTaskProc;
  1774. Result := Self;
  1775. end;
  1776. function TScheduledTask.OnException_Sync(aTaskProc: TTaskExceptionProc): IScheduledTask;
  1777. begin
  1778. Result := OnException(aTaskProc);
  1779. TTask(Result).ExceptionWithSync := True;
  1780. end;
  1781. function TScheduledTask.OnRetry(aTaskProc: TTaskRetryProc): IScheduledTask;
  1782. begin
  1783. fRetryProc := aTaskProc;
  1784. Result := Self;
  1785. end;
  1786. function TScheduledTask.OnExpired(aTaskProc: TTaskProc): IScheduledTask;
  1787. begin
  1788. fExpiredProc := aTaskProc;
  1789. Result := Self;
  1790. end;
  1791. function TScheduledTask.OnExpired_Sync(aTaskProc: TTaskProc): IScheduledTask;
  1792. begin
  1793. Result := OnExpired(aTaskProc);
  1794. TScheduledTask(Result).ExpireWithSync := True;
  1795. end;
  1796. function TScheduledTask.OnInitialize(aTaskProc: TTaskProc): IScheduledTask;
  1797. begin
  1798. fInitializeProc := aTaskProc;
  1799. Result := Self;
  1800. end;
  1801. function TScheduledTask.OnTerminated(aTaskProc: TTaskProc): IScheduledTask;
  1802. begin
  1803. fTerminateProc := aTaskProc;
  1804. Result := Self;
  1805. end;
  1806. function TScheduledTask.OnTerminated_Sync(aTaskProc: TTaskProc): IScheduledTask;
  1807. begin
  1808. Result := OnTerminated(aTaskProc);
  1809. TTask(Result).TerminateWithSync := True;
  1810. end;
  1811. { TScheduler }
  1812. constructor TScheduler.Create(aTaskList : TScheduledTaskList);
  1813. begin
  1814. inherited Create(True);
  1815. FreeOnTerminate := False;
  1816. fListLock := TCriticalSection.Create;
  1817. fRemoveTaskAfterExpiration := False;
  1818. fTaskList := aTaskList;
  1819. {$IFDEF FPC}
  1820. fCondVar := TSimpleEvent.Create;
  1821. {$ELSE}
  1822. fCondVar := TSimpleEvent.Create(nil,True,False,'');
  1823. {$ENDIF}
  1824. end;
  1825. destructor TScheduler.Destroy;
  1826. begin
  1827. fCondVar.SetEvent;
  1828. fCondVar.Free;
  1829. fTaskList := nil;
  1830. fListLock.Free;
  1831. inherited;
  1832. end;
  1833. procedure TScheduler.Execute;
  1834. var
  1835. task : IScheduledTask;
  1836. worker : TScheduledWorker;
  1837. numworker : Int64;
  1838. begin
  1839. numworker := 0;
  1840. while not Terminated do
  1841. begin
  1842. fListLock.Enter;
  1843. try
  1844. for task in fTaskList do
  1845. begin
  1846. if (task.IsEnabled) and (not task.IsFinished) then
  1847. begin
  1848. if task.CheckSchedule then
  1849. begin
  1850. Inc(numworker);
  1851. worker := TScheduledWorker.Create(numworker,task);
  1852. worker.Start;
  1853. end;
  1854. end
  1855. else
  1856. begin
  1857. if task.IsEnabled then
  1858. begin
  1859. //if TScheduledTask(task).ExpireWithSync then Synchronize(ExpireTask)
  1860. // else task.DoExpire;
  1861. if fRemoveTaskAfterExpiration then fTaskList.Remove(task);
  1862. end;
  1863. end;
  1864. end;
  1865. task := nil;
  1866. finally
  1867. fListLock.Leave;
  1868. end;
  1869. fCondVar.WaitFor(250);
  1870. end;
  1871. end;
  1872. function TScheduler.Add(aTask: TScheduledTask): Integer;
  1873. begin
  1874. Result := fTaskList.Add(aTask);
  1875. end;
  1876. function TScheduler.Get(aIdTask: Int64): IScheduledTask;
  1877. var
  1878. task : IScheduledTask;
  1879. begin
  1880. fListLock.Enter;
  1881. try
  1882. for task in fTaskList do
  1883. begin
  1884. if task.IdTask = aIdTask then Exit(task);
  1885. end;
  1886. finally
  1887. fListLock.Leave;
  1888. end;
  1889. end;
  1890. function TScheduler.Get(const aTaskName: string): IScheduledTask;
  1891. var
  1892. task : IScheduledTask;
  1893. begin
  1894. fListLock.Enter;
  1895. try
  1896. for task in fTaskList do
  1897. begin
  1898. if CompareText(task.Name,aTaskName) = 0 then Exit(task);
  1899. end;
  1900. finally
  1901. fListLock.Leave;
  1902. end;
  1903. end;
  1904. { TAdvThread }
  1905. constructor TAdvThread.Create(aProc : TProc; aSynchronize : Boolean);
  1906. begin
  1907. inherited Create(True);
  1908. FreeOnTerminate := True;
  1909. fExecuteWithSync := aSynchronize;
  1910. fExecuteProc := aProc;
  1911. end;
  1912. procedure TAdvThread.DoExecute;
  1913. begin
  1914. try
  1915. if Assigned(fExecuteProc) then fExecuteProc;
  1916. except
  1917. on E : Exception do
  1918. begin
  1919. {$IFNDEF FPC}
  1920. if Assigned(fExceptionProc) then fExceptionProc(AcquireExceptionObject as Exception)
  1921. {$ELSE}
  1922. if Assigned(fExceptionProc) then fExceptionProc(Exception(AcquireExceptionObject))
  1923. {$ENDIF}
  1924. else raise e;
  1925. end;
  1926. end;
  1927. end;
  1928. procedure TAdvThread.CallToTerminate;
  1929. begin
  1930. if Assigned(fTerminateProc) then fTerminateProc;
  1931. end;
  1932. procedure TAdvThread.DoTerminate;
  1933. begin
  1934. if fTerminateWithSync then Synchronize(CallToTerminate)
  1935. else CallToTerminate;
  1936. end;
  1937. procedure TAdvThread.Execute;
  1938. begin
  1939. if fExecuteWithSync then Synchronize(DoExecute)
  1940. else DoExecute;
  1941. end;
  1942. procedure TAdvThread.OnException(aProc: TAnonExceptionProc);
  1943. begin
  1944. fExceptionProc := aProc;
  1945. end;
  1946. procedure TAdvThread.OnTerminate(aProc: TProc; aSynchronize: Boolean);
  1947. begin
  1948. fTerminateWithSync := aSynchronize;
  1949. fTerminateProc := aProc;
  1950. end;
  1951. { TRunTask }
  1952. class function TRunTask.Execute(aTaskProc: TTaskProc): IWorkTask;
  1953. begin
  1954. Result := Execute([],False,aTaskProc);
  1955. end;
  1956. class function TRunTask.Execute_Sync(aTaskProc: TTaskProc): IWorkTask;
  1957. begin
  1958. Result := Execute_Sync([],False,aTaskProc);
  1959. end;
  1960. class function TRunTask.Execute(aParamArray: array of const; aOwnedParams: Boolean; aTaskProc: TTaskProc): IWorkTask;
  1961. var
  1962. task : TWorkTask;
  1963. worker : TSimpleWorker;
  1964. begin
  1965. task := TWorkTask.Create(aParamArray,aOwnedParams,aTaskProc);
  1966. task.ExecuteWithSync := False;
  1967. Result := task;
  1968. worker := TSimpleWorker.Create(task);
  1969. worker.Start;
  1970. end;
  1971. class function TRunTask.Execute_Sync(aParamArray: array of const; aOwnedParams: Boolean; aTaskProc: TTaskProc): IWorkTask;
  1972. var
  1973. task : TWorkTask;
  1974. worker : TSimpleWorker;
  1975. begin
  1976. task := TWorkTask.Create(aParamArray,aOwnedParams,aTaskProc);
  1977. task.ExecuteWithSync := True;
  1978. Result := task;
  1979. worker := TSimpleWorker.Create(task);
  1980. worker.Start;
  1981. end;
  1982. { TParamValue }
  1983. constructor TParamValue.Create(const aName: string; aValue: TFlexValue; aOwnedValue: Boolean);
  1984. begin
  1985. inherited Create;
  1986. fName := aName;
  1987. fValue := aValue;
  1988. fOwned := aOwnedValue;
  1989. end;
  1990. constructor TParamValue.Create(const aName: string; aValue: TVarRec; aOwnedValue: Boolean);
  1991. begin
  1992. inherited Create;
  1993. fName := aName;
  1994. fValue := aValue;
  1995. fOwned := aOwnedValue;
  1996. end;
  1997. constructor TParamValue.Create;
  1998. begin
  1999. fName := '';
  2000. fOwned := False;
  2001. end;
  2002. destructor TParamValue.Destroy;
  2003. begin
  2004. {$IFDEF FPC}
  2005. fValue._Release;
  2006. {$ENDIF}
  2007. if (fOwned) and (fValue.IsObject) and (fValue.AsObject <> nil) then fValue.AsObject.Free;
  2008. inherited;
  2009. end;
  2010. end.