forked from grijjy/GrijjyFoundation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Grijjy.TimerQueue.pas
702 lines (595 loc) · 16.7 KB
/
Grijjy.TimerQueue.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
unit Grijjy.TimerQueue;
{ Cross platform thread pool timer queue }
{ This class provides a method to execute timer events in a thread
that occur outside of the main application or UI thread. Most operating
systems provide an efficient kernel managed thread pool specificially for
threaded timers and we utilize that in this class for each OS. }
{ On Windows we use the CreateTimerQueueTimer() API to allow the OS/kernel to manage
the thread pool and callback.
On Android we use the JScheduledThreadPoolExecutor class and JRunnable to allow
the OS to manage the thread pool
On macOS/iOS we use the Grand Central Dispatcher and allow the OS
the OS to manage the thread pool
On Linux64 we use Epoll and the TimerFd capability to signal timer events
along with our own managed thread pool
Note: On some platforms the timer callback will only fire after the previous iteration
has completed, but on other platforms the callback will overlap at the interval.
}
{$I Grijjy.inc}
interface
uses
System.Classes,
System.SysUtils,
{$IF Defined(MSWINDOWS)}
Winapi.Windows,
{$ELSEIF Defined(ANDROID)}
Androidapi.JNI.Os,
Androidapi.JNI.JavaTypes,
Androidapi.JNI.JavaUtil,
Androidapi.JNIBridge,
{$ELSEIF Defined(LINUX)}
Posix.Time,
Linuxapi.Timerfd,
Linuxapi.Epoll,
{$ELSEIF Defined(IOS)}
iOSapi.CocoaTypes,
Macapi.CoreServices,
Macapi.Dispatch,
Macapi.Gcd,
Grijjy.CodeBlocks,
{$ELSEIF Defined(MACOS)}
Macapi.CocoaTypes,
Macapi.CoreServices,
Macapi.Dispatch,
Macapi.Gcd,
Grijjy.CodeBlocks,
{$ELSE}
{$MESSAGE Error 'Unsupported platform'}
{$ENDIF}
System.Generics.Collections,
System.SyncObjs,
System.DateUtils;
const
// Default size of the scheduled thread pool executor
ANDROID_THREAD_POOL_SIZE = 5;
const
INVALID_HANDLE_VALUE = THandle(-1);
// EPoll consts
IGNORED = 1;
MAX_EVENTS = 1024;
{$IFDEF ANDROID}
// Workaround for Delphi interface for JScheduledFuture, not inheriting properly
// from JFuture
type
_JScheduledThreadPoolExecutor = interface;
_JScheduledFutureClass = interface(JFutureClass)
['{4540CECE-4394-4969-AAAF-8C40ED55DAB8}']
end;
[JavaSignature('java/util/concurrent/ScheduledFuture')]
_JScheduledFuture = interface(JFuture)
['{1705E2E4-32D7-420F-B98C-7A646E26EA3F}']
end;
_TJScheduledFuture = class(TJavaGenericImport<_JScheduledFutureClass, _JScheduledFuture>) end;
_JScheduledThreadPoolExecutorClass = interface(JThreadPoolExecutorClass)
['{E97835A3-4211-4A02-AC53-E0951A70BFCE}']
{class} function init(corePoolSize: Integer): _JScheduledThreadPoolExecutor; cdecl; overload;
{class} function init(corePoolSize: Integer; threadFactory: JThreadFactory): _JScheduledThreadPoolExecutor; cdecl; overload;
{class} function init(corePoolSize: Integer; handler: JRejectedExecutionHandler): _JScheduledThreadPoolExecutor; cdecl; overload;
{class} function init(corePoolSize: Integer; threadFactory: JThreadFactory; handler: JRejectedExecutionHandler): _JScheduledThreadPoolExecutor; cdecl; overload;
end;
[JavaSignature('java/util/concurrent/ScheduledThreadPoolExecutor')]
_JScheduledThreadPoolExecutor = interface(JThreadPoolExecutor)
['{AE701E15-A4FE-4EDA-A9DE-0953F361F123}']
function scheduleAtFixedRate(command: JRunnable; initialDelay: Int64; period: Int64; unit_: JTimeUnit): _JScheduledFuture; cdecl;
end;
_TJScheduledThreadPoolExecutor = class(TJavaGenericImport<_JScheduledThreadPoolExecutorClass, _JScheduledThreadPoolExecutor>) end;
{$ENDIF}
type
TgoTimer = class;
TgoTimerQueue = class;
TOnTimer = procedure(const ASender: TObject) of object;
// Timer object
TgoTimer = class(TObject)
private
[weak] FTimerQueue: TgoTimerQueue;
FInterval: Cardinal;
FOnTimer: TOnTimer;
FHandle: THandle;
private
{$IFDEF LINUX}
FClose: Boolean;
FClosed: TEvent;
{$ENDIF}
{$IFDEF ANDROID}
FRunnable: JRunnable;
FScheduledFuture: _JScheduledFuture;
{$ENDIF}
{$IFDEF MACOS}
FDispatchTimer: dispatch_source_t;
{$ENDIF}
private
{$IFDEF ANDROID}
type
TAndroidRunnable = class(TJavaLocal, JRunnable)
private
FTimer: TgoTimer;
public
constructor Create(const ATimer: TgoTimer);
procedure run; cdecl;
end;
{$ENDIF}
protected
procedure SetInterval(const AInterval: Cardinal);
public
constructor Create(const ATimerQueue: TgoTimerQueue; const AInterval: Cardinal; const AOnTimer: TOnTimer);
destructor Destroy; override;
public
// Handle of the timer object
property Handle: THandle read FHandle;
// Timer interval in milliseconds
property Interval: Cardinal read FInterval write SetInterval;
// Timer callback
property OnTimer: TOnTimer read FOnTimer write FOnTimer;
end;
// Timer queue instance
TgoTimerQueue = class(TObject)
private
{$IFDEF MSWINDOWS}
FHandleTimerQueue: THandle;
{$ENDIF}
{$IFDEF MACOS}
FGlobalQueue: dispatch_queue_t;
{$ENDIF}
private
procedure ReleaseAll;
{$IFDEF MACOS}
function GetGlobalQueue: dispatch_queue_t;
{$ENDIF}
public
constructor Create;
destructor Destroy; override;
public
// Adds a new timer to the queue
function Add(const AInterval: Cardinal; const AOnTimer: TOnTimer): THandle;
// Release an existing timer
procedure Release(const AHandle: THandle);
// Change the internal rate of a timer
function SetInterval(const AHandle: THandle; const AInterval: Cardinal): Boolean;
public
{$IFDEF MSWINDOWS}
property HandleTimerQueue: THandle read FHandleTimerQueue;
{$ENDIF}
{$IFDEF MACOS}
property GlobalQueue: dispatch_queue_t read GetGlobalQueue;
{$ENDIF}
end;
{$IFDEF LINUX}
// Linux Epoll timer queue worker thread
TTimerQueuePool = class;
TTimerQueueWorker = class(TThread)
private
FOwner: TTimerQueuePool;
FEvents: array[0..MAX_EVENTS] of epoll_event;
protected
procedure Execute; override;
public
constructor Create(const AOwner: TTimerQueuePool);
destructor Destroy; override;
end;
// Linux Epoll timer queue pool
TTimerQueuePool = class(TObject)
private
FHandle: THandle;
FWorkers: array of TTimerQueueWorker;
public
constructor Create(const AWorkers: Integer = 0);
destructor Destroy; override;
public
// EPoll_fd for instance
property Handle: THandle read FHandle;
end;
{$ENDIF}
implementation
{$IFDEF LINUX}
uses
Posix.Unistd,
Posix.ErrNo;
{$ENDIF}
var
_Timers: TObjectDictionary<THandle, TgoTimer>;
_TimersLock: TCriticalSection;
_TimersHandle: THandle = 0;
{$IFDEF LINUX}
_TimerQueuePool: TTimerQueuePool;
{$ENDIF}
{$IFDEF ANDROID}
ScheduledThreadPoolExecutor: _JScheduledThreadPoolExecutor;
{$ENDIF}
{ Helpers }
procedure _Lock;
begin
_TimersLock.Enter;
end;
procedure _Unlock;
begin
_TimersLock.Leave;
end;
{$IFDEF MSWINDOWS}
procedure WaitOrTimerCallback(Timer: TgoTimer; TimerOrWaitFired: ByteBool); stdcall;
begin
if Assigned(Timer) then
begin
_Lock;
try
if not _Timers.ContainsKey(Timer.Handle) then
Exit;
finally
_Unlock;
end;
if TimerOrWaitFired then
if Assigned(Timer.OnTimer) then
Timer.OnTimer(Timer);
end;
end;
{$ENDIF}
{ TgoTimer }
constructor TgoTimer.Create(const ATimerQueue: TgoTimerQueue; const AInterval: Cardinal; const AOnTimer: TOnTimer);
{$IFDEF LINUX}
var
Event: epoll_event;
{$ENDIF}
begin
inherited Create;
FTimerQueue := ATimerQueue;
FInterval := AInterval;
FOnTimer := AOnTimer;
{$IF Defined(MSWINDOWS)}
if not CreateTimerQueueTimer(FHandle, ATimerQueue.HandleTimerQueue, @WaitOrTimerCallback, Self, 0, AInterval, 0) then
FHandle := INVALID_HANDLE_VALUE;
{$ELSEIF Defined(ANDROID)}
FHandle := AtomicIncrement(_TimersHandle);
// With scheduleWithFixedDelay(), the scheduler will wait for the task to complete
// and then wait for five seconds before executing it again.
// With scheduleWithFixedRate() if you set the period to five seconds then it
// means that every five seconds your task will be executed
FRunnable := TAndroidRunnable.Create(Self);
FScheduledFuture := ScheduledThreadPoolExecutor.scheduleAtFixedRate(FRunnable, AInterval, AInterval, TJTimeUnit.JavaClass.MILLISECONDS);
{$ELSEIF Defined(LINUX)}
FHandle := INVALID_HANDLE_VALUE;
FClose := False;
FClosed := TEvent.Create(nil, True, False, '');
// Create a non-blocking timer descriptor
FHandle := timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK);
if FHandle <> -1 then
begin
// Add descriptor to the set
Event.data.ptr := Self;
Event.events := EPOLLIN or EPOLLET;
if epoll_ctl(_TimerQueuePool.Handle, EPOLL_CTL_ADD, FHandle, @Event) <> -1 then
// start the timer
SetInterval(AInterval)
else
__close(FHandle);
end;
{$ELSEIF Defined(MACOS)}
FHandle := AtomicIncrement(_TimersHandle);
FDispatchTimer := dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, FTimerQueue.GlobalQueue);
if Assigned(FDispatchTimer) then
begin
dispatch_source_set_timer(FDispatchTimer,
dispatch_time(DISPATCH_TIME_NOW, AInterval * NSEC_PER_MSEC), // Start delay
AInterval * NSEC_PER_MSEC, // Interval
0); // Leeway
dispatch_source_set_event_handler(FDispatchTimer,
TObjCBlock.CreateBlockWithProcedure(
procedure(p1: NSInteger; p2: Pointer)
begin
if Assigned(FOnTimer) then
FOnTimer(Self);
end));
dispatch_resume(FDispatchTimer);
end;
{$ENDIF}
end;
destructor TgoTimer.Destroy;
begin
{$IF Defined(MSWINDOWS)}
// DeleteTimerQueueTimer API will block until all the callbacks are completed
DeleteTimerQueueTimer(FTimerQueue.HandleTimerQueue, FHandle, INVALID_HANDLE_VALUE);
{$ELSEIF Defined(ANDROID)}
ScheduledThreadPoolExecutor.remove(FRunnable);
{$ELSEIF Defined(LINUX)}
FClose := True;
// Timeout quickly
SetInterval(1);
// Wait for closed signal
FClosed.WaitFor(INFINITE);
FClosed.Free;
{$ELSEIF Defined(MACOS)}
dispatch_source_cancel(FDispatchTimer);
FDispatchTimer := nil;
{$ENDIF}
inherited;
end;
procedure TgoTimer.SetInterval(const AInterval: Cardinal);
{$IFDEF LINUX}
var
NewValue: itimerspec;
TS: timespec;
{$ENDIF}
begin
{$IF Defined(MSWINDOWS)}
if not ChangeTimerQueueTimer(FTimerQueue.HandleTimerQueue, FHandle, 0, AInterval) then
Exit;
{$ELSEIF Defined(ANDROID)}
FScheduledFuture.cancel(True);
FScheduledFuture := ScheduledThreadPoolExecutor.scheduleAtFixedRate(FRunnable, AInterval, AInterval, TJTimeUnit.JavaClass.MILLISECONDS);
{$ELSEIF Defined(LINUX)}
FillChar(NewValue, SizeOf(itimerspec), 0);
TS.tv_sec := AInterval DIV 1000;
TS.tv_nsec := (AInterval MOD 1000) * 1000000;
NewValue.it_value := TS;
NewValue.it_interval := TS;
if timerfd_settime(FHandle, 0, @NewValue, nil) = -1 then
Exit;
{$ELSEIF Defined(MACOS)}
if Assigned(FDispatchTimer) then
dispatch_source_set_timer(FDispatchTimer,
dispatch_time(DISPATCH_TIME_NOW, AInterval * NSEC_PER_MSEC),
AInterval * NSEC_PER_MSEC, 0);
{$ENDIF}
FInterval := AInterval;
end;
{ TgoTimerQueue }
constructor TgoTimerQueue.Create;
begin
{$IF Defined(MSWINDOWS)}
FHandleTimerQueue := CreateTimerQueue;
{$ELSEIF Defined(ANDROID)}
{$ELSEIF Defined(LINUX)}
{$ELSEIF Defined(MACOS)}
{$ENDIF}
end;
destructor TgoTimerQueue.Destroy;
begin
ReleaseAll;
{$IF Defined(MSWINDOWS)}
DeleteTimerQueueEx(FHandleTimerQueue, INVALID_HANDLE_VALUE);
FHandleTimerQueue := INVALID_HANDLE_VALUE;
{$ELSEIF Defined(ANDROID)}
{$ELSEIF Defined(LINUX)}
{$ELSEIF Defined(MACOS)}
FGlobalQueue := nil;
{$ENDIF}
{$IFDEF MSWINDOWS}
{$ENDIF}
end;
{$IFDEF MACOS}
function TgoTimerQueue.GetGlobalQueue: dispatch_queue_t;
begin
if FGlobalQueue = nil then
FGlobalQueue := dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
Result := FGlobalQueue;
end;
{$ENDIF}
function TgoTimerQueue.Add(const AInterval: Cardinal; const AOnTimer: TOnTimer): THandle;
var
Timer: TgoTimer;
begin
// Create a timer object
Timer := TgoTimer.Create(Self, AInterval, AOnTimer);
_Lock;
try
_Timers.Add(Timer.Handle, Timer);
Result := Timer.Handle;
finally
_Unlock;
end;
end;
procedure TgoTimerQueue.Release(const AHandle: THandle);
var
TimerPair: TPair<THandle, TgoTimer>;
Timer: TgoTimer;
begin
_Lock;
try
if not _Timers.ContainsKey(AHandle) then
Exit;
TimerPair := _Timers.ExtractPair(AHandle);
Timer := TimerPair.Value;
finally
_Unlock;
end;
// Stop any events
Timer.OnTimer := nil;
// Destroy
{$IFNDEF NEXTGEN}
Timer.Free;
{$ENDIF}
end;
procedure TgoTimerQueue.ReleaseAll;
var
TimerPair: TPair<THandle, TgoTimer>;
Timers: TArray<TgoTimer>;
Timer: TgoTimer;
Handle: THandle;
begin
_Lock;
try
for Handle in _Timers.Keys.ToArray do
begin
TimerPair := _Timers.ExtractPair(Handle);
Timers := Timers + [TimerPair.Value];
end;
_Timers.Clear;
finally
_Unlock;
end;
// Destroy all timers
for Timer in Timers do
begin
Timer.OnTimer := nil;
{$IFNDEF NEXTGEN}
Timer.Free;
{$ENDIF}
end;
end;
function TgoTimerQueue.SetInterval(const AHandle: THandle; const AInterval: Cardinal): Boolean;
var
Timer: TgoTimer;
begin
_Lock;
try
if not _Timers.TryGetValue(AHandle, Timer) then
Exit(False);
Timer.Interval := AInterval;
Result := True;
finally
_Unlock;
end;
end;
{$IFDEF ANDROID}
{ TgoTimer.TAndroidRunnable }
constructor TgoTimer.TAndroidRunnable.Create(const ATimer: TgoTimer);
begin
inherited Create;
FTimer := ATimer;
end;
procedure TgoTimer.TAndroidRunnable.run;
begin
if Assigned(FTimer.OnTimer) then
FTimer.OnTimer(FTimer);
end;
{$ENDIF}
{$IFDEF LINUX}
{ TTimerQueueWorker }
constructor TTimerQueueWorker.Create(const AOwner: TTimerQueuePool);
begin
FOwner := AOwner;
inherited Create(False);
end;
destructor TTimerQueueWorker.Destroy;
begin
inherited;
end;
procedure TTimerQueueWorker.Execute;
var
NumberOfEvents: Integer;
I: Integer;
Event: epoll_event;
TotalTimeouts: Int64;
Timer: TgoTimer;
Error: Integer;
begin
while not Terminated do
begin
NumberOfEvents := epoll_wait(FOwner.Handle, @FEvents, MAX_EVENTS, 100);
if NumberOfEvents = 0 then // Timeout
Continue
else
if NumberOfEvents = -1 then // Error
begin
Error := errno;
if Error = EINTR then
Continue
else
Break;
end;
for I := 0 to NumberOfEvents - 1 do
begin
try
Timer := FEvents[I].data.ptr;
if not Timer.FClose then
begin
if (FEvents[I].events AND EPOLLIN) = EPOLLIN then
begin
if __read(Timer.Handle, @TotalTimeouts, SizeOf(TotalTimeouts)) >= 0 then
begin
if Assigned(Timer.FOnTimer) then
Timer.FOnTimer(Timer);
end
else
// Read error
Timer.FClose := True;
end;
end;
finally
if Timer.FClose then
begin
// Remove descriptor from the set
epoll_ctl(_TimerQueuePool.Handle, EPOLL_CTL_DEL, Timer.Handle, @Event); // -1 on error
// Close the timer handle
__close(Timer.Handle);
// Trigger closed event
Timer.FClosed.SetEvent;
end;
end;
end;
end;
end;
{ TTimerQueuePool }
constructor TTimerQueuePool.Create(const AWorkers: Integer);
var
I: Integer;
Workers: Integer;
begin
inherited Create;
// Create the epoll instance handle
FHandle := epoll_create(IGNORED);
if FHandle <> -1 then
begin
// Create worker threads to handle queued events
if AWorkers = 0 then
Workers := CPUCount
else
Workers := AWorkers;
SetLength(FWorkers, Workers);
for I := 0 to Workers - 1 do
FWorkers[I] := TTimerQueueWorker.Create(Self);
end
else
raise Exception.Create(Format('epoll_create failed %s',[SysErrorMessage(errno)]));
end;
destructor TTimerQueuePool.Destroy;
var
Worker: TTimerQueueWorker;
begin
// Signal the workers to quit
for Worker in FWorkers do
Worker.Terminate;
// Wait for them to stop
for Worker in FWorkers do
Worker.WaitFor;
// Destroy workers
for Worker in FWorkers do
Worker.DisposeOf;
// Close the epoll instance handle
if FHandle <> -1 then
__close(FHandle);
inherited Destroy;
end;
{$ENDIF}
initialization
_Timers := TObjectDictionary<THandle, TgoTimer>.Create([doOwnsValues]);
_TimersLock := TCriticalSection.Create;
{$IFDEF LINUX}
_TimerQueuePool := TTimerQueuePool.Create;
{$ENDIF}
{$IFDEF ANDROID}
ScheduledThreadPoolExecutor := _TJScheduledThreadPoolExecutor.JavaClass.init(ANDROID_THREAD_POOL_SIZE);
{$ENDIF}
finalization
_Lock;
try
_Timers.Free;
finally
_Unlock;
end;
_TimersLock.Free;
{$IFDEF LINUX}
_TimerQueuePool.Free;
{$ENDIF}
{$IFDEF ANDROID}
ScheduledThreadPoolExecutor := nil;
{$ENDIF}
end.