PyEventEngine 0.6.0.post3__cp313-cp313-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. event_engine/__infra__.pxd +2 -0
  2. event_engine/__init__.pxd +2 -0
  3. event_engine/__init__.py +37 -0
  4. event_engine/base/__infra__.pxd +9 -0
  5. event_engine/base/__init__.pxd +9 -0
  6. event_engine/base/__init__.py +82 -0
  7. event_engine/base/c_allocator_protocol.c +10817 -0
  8. event_engine/base/c_allocator_protocol.cp313-win_amd64.pyd +0 -0
  9. event_engine/base/c_allocator_protocol.h +23 -0
  10. event_engine/base/c_allocator_protocol.pxd +31 -0
  11. event_engine/base/c_allocator_protocol.pyx +99 -0
  12. event_engine/capi/__infra__.pxd +189 -0
  13. event_engine/capi/__init__.pxd +189 -0
  14. event_engine/capi/__init__.py +84 -0
  15. event_engine/capi/c_engine.c +28711 -0
  16. event_engine/capi/c_engine.cp313-win_amd64.pyd +0 -0
  17. event_engine/capi/c_engine.h +393 -0
  18. event_engine/capi/c_engine.pxd +84 -0
  19. event_engine/capi/c_engine.pyi +424 -0
  20. event_engine/capi/c_engine.pyx +560 -0
  21. event_engine/capi/c_event.c +19921 -0
  22. event_engine/capi/c_event.cp313-win_amd64.pyd +0 -0
  23. event_engine/capi/c_event.h +342 -0
  24. event_engine/capi/c_event.pxd +159 -0
  25. event_engine/capi/c_event.pyi +226 -0
  26. event_engine/capi/c_event.pyx +387 -0
  27. event_engine/capi/c_topic.c +30978 -0
  28. event_engine/capi/c_topic.cp313-win_amd64.pyd +0 -0
  29. event_engine/capi/c_topic.h +1007 -0
  30. event_engine/capi/c_topic.pxd +147 -0
  31. event_engine/capi/c_topic.pyi +580 -0
  32. event_engine/capi/c_topic.pyx +725 -0
  33. event_engine/capi/fallback_engine.py +670 -0
  34. event_engine/includes/event_engine/base/c_allocator_protocol.c +10817 -0
  35. event_engine/includes/event_engine/base/c_allocator_protocol.h +23 -0
  36. event_engine/includes/event_engine/capi/c_engine.c +28711 -0
  37. event_engine/includes/event_engine/capi/c_engine.h +393 -0
  38. event_engine/includes/event_engine/capi/c_event.c +19921 -0
  39. event_engine/includes/event_engine/capi/c_event.h +342 -0
  40. event_engine/includes/event_engine/capi/c_topic.c +30978 -0
  41. event_engine/includes/event_engine/capi/c_topic.h +1007 -0
  42. event_engine/native/__init__.py +60 -0
  43. event_engine/native/_event.py +420 -0
  44. event_engine/native/_topic.py +171 -0
  45. event_engine/native/engine.py +746 -0
  46. event_engine/native/event.py +467 -0
  47. event_engine/native/topic.py +945 -0
  48. pyeventengine-0.6.0.post3.dist-info/METADATA +189 -0
  49. pyeventengine-0.6.0.post3.dist-info/RECORD +52 -0
  50. pyeventengine-0.6.0.post3.dist-info/WHEEL +5 -0
  51. pyeventengine-0.6.0.post3.dist-info/licenses/LICENSE +21 -0
  52. pyeventengine-0.6.0.post3.dist-info/top_level.txt +1 -0
@@ -0,0 +1,670 @@
1
+ """
2
+ Pure Python fallback implementation of EventEngine for cross-platform compatibility.
3
+
4
+ This module provides Python-native implementations of EventEngine and EventEngineEx
5
+ that work on Windows and other platforms without requiring Cython/C extensions.
6
+
7
+ Uses:
8
+ - threading.Lock, threading.Condition for synchronization
9
+ - dict for topic-to-hook mappings (instead of ByteMap)
10
+ - Topic, MessagePayload, EventHook from c_topic and c_event modules
11
+ """
12
+
13
+ import threading
14
+ from collections import deque
15
+ from datetime import datetime, timedelta
16
+ from logging import Logger
17
+ from threading import Thread
18
+ from time import sleep, time
19
+ from typing import Optional
20
+
21
+ from .c_event import EventHook, EventHookEx, MessagePayload
22
+ from .c_topic import Topic
23
+ from ..base import LOGGER
24
+
25
+ LOGGER = LOGGER.getChild('Event')
26
+
27
+ # Default constants (matching c_engine defaults)
28
+ DEFAULT_MQ_CAPACITY = 0x0fff
29
+ DEFAULT_MQ_SPIN_LIMIT = 0xffff
30
+ DEFAULT_MQ_TIMEOUT_SECONDS = 1.0
31
+
32
+
33
+ class Full(Exception):
34
+ """Exception raised when the message queue is full."""
35
+ pass
36
+
37
+
38
+ class Empty(Exception):
39
+ """Exception raised when the message queue is empty."""
40
+ pass
41
+
42
+
43
+ class EventEngine:
44
+ """
45
+ Pure Python implementation of EventEngine.
46
+
47
+ Uses dict-based topic-to-hook mappings and threading primitives for synchronization.
48
+ Compatible with Windows and all platforms supporting the threading module.
49
+ """
50
+
51
+ def __init__(self, capacity: int = DEFAULT_MQ_CAPACITY, logger: Optional[Logger] = None):
52
+ """
53
+ Initialize EventEngine.
54
+
55
+ Args:
56
+ capacity: Maximum capacity of the message queue
57
+ logger: Optional logger instance
58
+ """
59
+ self.logger = LOGGER.getChild('EventEngine') if logger is None else logger
60
+
61
+ # Message queue using deque with threading primitives
62
+ self._capacity = capacity
63
+ self._queue = deque(maxlen=capacity)
64
+ self._lock = threading.Lock()
65
+ self._not_empty = threading.Condition(self._lock)
66
+ self._not_full = threading.Condition(self._lock)
67
+
68
+ # Topic-to-hook mappings using dict (key: topic.value string)
69
+ self._exact_topic_hooks: dict[str, EventHook] = {}
70
+ self._generic_topic_hooks: dict[str, EventHook] = {}
71
+
72
+ # Sequence ID counter
73
+ self._seq_id = 0
74
+
75
+ # Engine state
76
+ self.active = False
77
+ self.engine: Optional[Thread] = None
78
+
79
+ def __len__(self) -> int:
80
+ """Return the total number of registered hooks."""
81
+ return len(self._exact_topic_hooks) + len(self._generic_topic_hooks)
82
+
83
+ def __repr__(self) -> str:
84
+ """String representation of the engine."""
85
+ return f'<{self.__class__.__name__} {"active" if self.active else "idle"}>(capacity={self.capacity})'
86
+
87
+ def _loop(self):
88
+ """Main event loop - consumes and processes messages."""
89
+ while self.active:
90
+ msg = self._get_message(block=True, timeout=DEFAULT_MQ_TIMEOUT_SECONDS)
91
+ if msg is not None:
92
+ self._trigger(msg)
93
+
94
+ def _get_message(self, block: bool = True, timeout: float = 0.0) -> Optional[MessagePayload]:
95
+ """
96
+ Get a message from the queue.
97
+
98
+ Args:
99
+ block: Whether to block if queue is empty
100
+ timeout: Timeout in seconds (0 means no timeout)
101
+
102
+ Returns:
103
+ MessagePayload or None if timeout/non-blocking and queue is empty
104
+ """
105
+ with self._not_empty:
106
+ if not block:
107
+ if len(self._queue) == 0:
108
+ return None
109
+ return self._queue.popleft()
110
+
111
+ # Blocking mode
112
+ if timeout > 0:
113
+ end_time = time() + timeout
114
+ while len(self._queue) == 0 and self.active:
115
+ remaining = end_time - time()
116
+ if remaining <= 0:
117
+ return None
118
+ self._not_empty.wait(timeout=remaining)
119
+ else:
120
+ # No timeout - wait indefinitely
121
+ while len(self._queue) == 0 and self.active:
122
+ self._not_empty.wait(timeout=DEFAULT_MQ_TIMEOUT_SECONDS)
123
+
124
+ if len(self._queue) == 0:
125
+ return None
126
+
127
+ msg = self._queue.popleft()
128
+ self._not_full.notify()
129
+ return msg
130
+
131
+ def _publish(self, topic: Topic, args: tuple, kwargs: dict, block: bool = True, max_spin: int = DEFAULT_MQ_SPIN_LIMIT, timeout: float = 0.0) -> int:
132
+ """
133
+ Publish a message to the queue.
134
+
135
+ Args:
136
+ topic: Topic for the message
137
+ args: Positional arguments
138
+ kwargs: Keyword arguments
139
+ block: Whether to block if queue is full
140
+ max_spin: Spin limit (ignored in pure Python implementation)
141
+ timeout: Timeout in seconds
142
+
143
+ Returns:
144
+ 0 on success, non-zero on failure
145
+ """
146
+ if not topic.is_exact:
147
+ raise ValueError('Topic must be all of exact parts')
148
+
149
+ # Create payload
150
+ payload = MessagePayload(alloc=True)
151
+ payload.topic = topic
152
+ payload.args = args
153
+ payload.kwargs = kwargs
154
+ payload.seq_id = self._seq_id
155
+
156
+ # Note: args_owner and kwargs_owner must be False when publishing
157
+ payload.args_owner = False
158
+ payload.kwargs_owner = False
159
+
160
+ with self._not_full:
161
+ if not block:
162
+ if len(self._queue) >= self._capacity:
163
+ return 1 # Queue full
164
+ self._queue.append(payload)
165
+ self._seq_id += 1
166
+ self._not_empty.notify()
167
+ return 0
168
+
169
+ # Blocking mode
170
+ if timeout > 0:
171
+ end_time = time() + timeout
172
+ while len(self._queue) >= self._capacity:
173
+ remaining = end_time - time()
174
+ if remaining <= 0:
175
+ return 1 # Timeout
176
+ self._not_full.wait(timeout=remaining)
177
+ else:
178
+ # No timeout - wait indefinitely
179
+ while len(self._queue) >= self._capacity:
180
+ self._not_full.wait(timeout=DEFAULT_MQ_TIMEOUT_SECONDS)
181
+
182
+ if len(self._queue) >= self._capacity:
183
+ return 1 # Failed
184
+
185
+ self._queue.append(payload)
186
+ self._seq_id += 1
187
+ self._not_empty.notify()
188
+ return 0
189
+
190
+ def _trigger(self, msg: MessagePayload):
191
+ """
192
+ Trigger event hooks matching the message topic.
193
+
194
+ Args:
195
+ msg: Message payload to dispatch
196
+ """
197
+ msg_topic = msg.topic
198
+
199
+ # Step 1: Match exact topic hooks
200
+ hook = self._exact_topic_hooks.get(msg_topic.value)
201
+ if hook:
202
+ hook.trigger(msg)
203
+
204
+ # Step 2: Match generic topic hooks (wildcards, patterns, etc.)
205
+ for hook_topic_str, hook in self._generic_topic_hooks.items():
206
+ # Use topic matching from Topic
207
+ if hook.topic.match(msg_topic).matched:
208
+ hook.trigger(msg)
209
+
210
+ def _register_hook(self, hook: EventHook):
211
+ """
212
+ Register an event hook.
213
+
214
+ Args:
215
+ hook: EventHook to register
216
+ """
217
+ topic = hook.topic
218
+ topic_str = topic.value
219
+
220
+ if topic.is_exact:
221
+ if topic_str in self._exact_topic_hooks and self._exact_topic_hooks[topic_str] is not hook:
222
+ raise KeyError(f'Another EventHook already registered for {topic_str}')
223
+ self._exact_topic_hooks[topic_str] = hook
224
+ else:
225
+ if topic_str in self._generic_topic_hooks and self._generic_topic_hooks[topic_str] is not hook:
226
+ raise KeyError(f'Another EventHook already registered for {topic_str}')
227
+ self._generic_topic_hooks[topic_str] = hook
228
+
229
+ def _unregister_hook(self, topic: Topic) -> EventHook:
230
+ """
231
+ Unregister an event hook by topic.
232
+
233
+ Args:
234
+ topic: Topic of the hook to unregister
235
+
236
+ Returns:
237
+ The unregistered EventHook
238
+ """
239
+ topic_str = topic.value
240
+
241
+ if topic.is_exact:
242
+ if topic_str not in self._exact_topic_hooks:
243
+ raise KeyError(f'No EventHook registered for {topic_str}')
244
+ return self._exact_topic_hooks.pop(topic_str)
245
+ else:
246
+ if topic_str not in self._generic_topic_hooks:
247
+ raise KeyError(f'No EventHook registered for {topic_str}')
248
+ return self._generic_topic_hooks.pop(topic_str)
249
+
250
+ def _register_handler(self, topic: Topic, handler, deduplicate: bool = False):
251
+ """
252
+ Register a handler for a topic (creates hook if needed).
253
+
254
+ Args:
255
+ topic: Topic to register handler for
256
+ handler: Callable handler
257
+ deduplicate: Whether to skip if handler already registered
258
+ """
259
+ topic_str = topic.value
260
+
261
+ if topic.is_exact:
262
+ hook_map = self._exact_topic_hooks
263
+ else:
264
+ hook_map = self._generic_topic_hooks
265
+
266
+ if topic_str not in hook_map:
267
+ hook = EventHook(topic, self.logger)
268
+ hook_map[topic_str] = hook
269
+ else:
270
+ hook = hook_map[topic_str]
271
+
272
+ hook.add_handler(handler, deduplicate=deduplicate)
273
+
274
+ def _unregister_handler(self, topic: Topic, handler):
275
+ """
276
+ Unregister a handler from a topic.
277
+
278
+ Args:
279
+ topic: Topic to unregister handler from
280
+ handler: Callable handler to remove
281
+ """
282
+ topic_str = topic.value
283
+
284
+ if topic.is_exact:
285
+ hook_map = self._exact_topic_hooks
286
+ else:
287
+ hook_map = self._generic_topic_hooks
288
+
289
+ if topic_str not in hook_map:
290
+ raise KeyError(f'No EventHook registered for {topic_str}')
291
+
292
+ hook = hook_map[topic_str]
293
+ hook.remove_handler(handler)
294
+
295
+ # Remove hook if no handlers left
296
+ if len(hook) == 0:
297
+ del hook_map[topic_str]
298
+
299
+ def _clear(self):
300
+ """Clear all hooks and handlers."""
301
+ # Clear all hooks
302
+ for hook in self._exact_topic_hooks.values():
303
+ hook.clear()
304
+ self._exact_topic_hooks.clear()
305
+
306
+ for hook in self._generic_topic_hooks.values():
307
+ hook.clear()
308
+ self._generic_topic_hooks.clear()
309
+
310
+ # --- Public API ---
311
+
312
+ def activate(self):
313
+ """Activate the engine (sets active flag to True)."""
314
+ self.active = True
315
+
316
+ def deactivate(self):
317
+ """Deactivate the engine (sets active flag to False)."""
318
+ self.active = False
319
+
320
+ def run(self):
321
+ """Run the event loop (blocking call)."""
322
+ self._loop()
323
+
324
+ def start(self):
325
+ """Start the engine in a background thread."""
326
+ if self.active:
327
+ self.logger.warning(f'{self} already started!')
328
+ return
329
+ self.active = True
330
+ self.engine = Thread(target=self.run, name='EventEngine')
331
+ self.engine.start()
332
+ self.logger.info(f'{self} started.')
333
+
334
+ def stop(self):
335
+ """Stop the engine and wait for the background thread to finish."""
336
+ if not self.active:
337
+ self.logger.warning('EventEngine already stopped!')
338
+ return
339
+
340
+ self.active = False
341
+
342
+ # Wake up the event loop if it's waiting
343
+ with self._not_empty:
344
+ self._not_empty.notify_all()
345
+
346
+ if self.engine:
347
+ self.engine.join()
348
+
349
+ def clear(self):
350
+ """Clear all hooks and handlers (engine must be stopped first)."""
351
+ if self.active:
352
+ self.logger.error('EventEngine must be stopped before cleared!')
353
+ return
354
+
355
+ self._clear()
356
+
357
+ def get(self, block: bool = True, max_spin: int = DEFAULT_MQ_SPIN_LIMIT, timeout: float = 0.0) -> MessagePayload:
358
+ """
359
+ Get a message from the queue.
360
+
361
+ Args:
362
+ block: Whether to block if queue is empty
363
+ max_spin: Spin limit (ignored in pure Python)
364
+ timeout: Timeout in seconds
365
+
366
+ Returns:
367
+ MessagePayload
368
+
369
+ Raises:
370
+ Empty: If no message available
371
+ """
372
+ msg = self._get_message(block=block, timeout=timeout)
373
+ if msg is None:
374
+ raise Empty()
375
+
376
+ # When getting, payload must have args_owner = kwargs_owner = True
377
+ msg.args_owner = True
378
+ msg.kwargs_owner = True
379
+ return msg
380
+
381
+ def put(self, topic: Topic, *args, block: bool = True, max_spin: int = DEFAULT_MQ_SPIN_LIMIT, timeout: float = 0.0, **kwargs):
382
+ """
383
+ Put a message into the queue.
384
+
385
+ Args:
386
+ topic: Topic for the message
387
+ *args: Positional arguments
388
+ block: Whether to block if queue is full
389
+ max_spin: Spin limit (ignored)
390
+ timeout: Timeout in seconds
391
+ **kwargs: Keyword arguments
392
+
393
+ Raises:
394
+ Full: If queue is full
395
+ """
396
+ ret_code = self._publish(topic, args, kwargs, block, max_spin, timeout)
397
+ if ret_code:
398
+ raise Full()
399
+
400
+ def publish(self, topic: Topic, args: tuple, kwargs: dict, block: bool = True, max_spin: int = DEFAULT_MQ_SPIN_LIMIT, timeout: float = 0.0):
401
+ """
402
+ Publish a message to the queue.
403
+
404
+ Args:
405
+ topic: Topic for the message
406
+ args: Positional arguments tuple
407
+ kwargs: Keyword arguments dict
408
+ block: Whether to block if queue is full
409
+ max_spin: Spin limit (ignored)
410
+ timeout: Timeout in seconds
411
+
412
+ Raises:
413
+ Full: If queue is full
414
+ """
415
+ ret_code = self._publish(topic, args, kwargs, block, max_spin, timeout)
416
+ if ret_code:
417
+ raise Full()
418
+
419
+ def register_hook(self, hook: EventHook):
420
+ """
421
+ Register an event hook.
422
+
423
+ Args:
424
+ hook: EventHook instance to register
425
+ """
426
+ self._register_hook(hook)
427
+
428
+ def unregister_hook(self, topic: Topic) -> EventHook:
429
+ """
430
+ Unregister a hook by topic.
431
+
432
+ Args:
433
+ topic: Topic of the hook to unregister
434
+
435
+ Returns:
436
+ The unregistered EventHook
437
+ """
438
+ return self._unregister_hook(topic)
439
+
440
+ def register_handler(self, topic: Topic, handler, deduplicate: bool = False):
441
+ """
442
+ Register a handler for a topic.
443
+
444
+ Args:
445
+ topic: Topic to register handler for
446
+ handler: Callable handler
447
+ deduplicate: Skip if handler already registered
448
+ """
449
+ self._register_handler(topic, handler, deduplicate)
450
+
451
+ def unregister_handler(self, topic: Topic, handler):
452
+ """
453
+ Unregister a handler from a topic.
454
+
455
+ Args:
456
+ topic: Topic to unregister handler from
457
+ handler: Callable handler to remove
458
+ """
459
+ self._unregister_handler(topic, handler)
460
+
461
+ def event_hooks(self):
462
+ """Iterate over all registered event hooks."""
463
+ yield from self._exact_topic_hooks.values()
464
+ yield from self._generic_topic_hooks.values()
465
+
466
+ def topics(self):
467
+ """Iterate over all registered topics."""
468
+ for hook in self.event_hooks():
469
+ yield hook.topic
470
+
471
+ def items(self):
472
+ """Iterate over (topic, hook) pairs."""
473
+ for hook in self.event_hooks():
474
+ yield (hook.topic, hook)
475
+
476
+ @property
477
+ def capacity(self) -> int:
478
+ """Get the queue capacity."""
479
+ return self._capacity
480
+
481
+ @property
482
+ def occupied(self) -> int:
483
+ """Get the current number of messages in the queue."""
484
+ with self._lock:
485
+ return len(self._queue)
486
+
487
+ @property
488
+ def exact_topic_hook_map(self) -> dict:
489
+ """Get the exact topic hook mapping."""
490
+ return self._exact_topic_hooks.copy()
491
+
492
+ @property
493
+ def generic_topic_hook_map(self) -> dict:
494
+ """Get the generic topic hook mapping."""
495
+ return self._generic_topic_hooks.copy()
496
+
497
+
498
+ class EventEngineEx(EventEngine):
499
+ """
500
+ Extended EventEngine with timer support.
501
+
502
+ Provides timer functionality for periodic event triggering.
503
+ """
504
+
505
+ def __init__(self, capacity: int = DEFAULT_MQ_CAPACITY, logger: Optional[Logger] = None):
506
+ """
507
+ Initialize EventEngineEx.
508
+
509
+ Args:
510
+ capacity: Maximum capacity of the message queue
511
+ logger: Optional logger instance
512
+ """
513
+ super().__init__(capacity, logger)
514
+ self.timer: dict[float, Thread] = {}
515
+
516
+ def __repr__(self) -> str:
517
+ """String representation including active timers."""
518
+ return (f'<{self.__class__.__name__} {"active" if self.active else "idle"}>'
519
+ f'(capacity={self.capacity}, timers={list(self.timer.keys())})')
520
+
521
+ def _timer_loop(self, interval: float, topic: Topic, activate_time: Optional[datetime]):
522
+ """
523
+ Timer loop for custom intervals.
524
+
525
+ Args:
526
+ interval: Interval in seconds
527
+ topic: Topic to publish on
528
+ activate_time: Optional activation time
529
+ """
530
+ if activate_time is None:
531
+ scheduled_time = datetime.now()
532
+ else:
533
+ scheduled_time = activate_time
534
+
535
+ kwargs = {'interval': interval, 'trigger_time': scheduled_time}
536
+
537
+ while self.active:
538
+ sleep_time = (scheduled_time - datetime.now()).total_seconds()
539
+
540
+ if sleep_time > 0:
541
+ sleep(sleep_time)
542
+
543
+ self._publish(topic, (), kwargs, True, DEFAULT_MQ_SPIN_LIMIT, 0.0)
544
+
545
+ while scheduled_time < datetime.now():
546
+ scheduled_time += timedelta(seconds=interval)
547
+ kwargs['trigger_time'] = scheduled_time
548
+
549
+ def _minute_timer_loop(self, topic: Topic):
550
+ """
551
+ Minute-aligned timer loop.
552
+
553
+ Args:
554
+ topic: Topic to publish on
555
+ """
556
+ kwargs = {'interval': 60}
557
+
558
+ while self.active:
559
+ t = time()
560
+ scheduled_time = t // 60 * 60
561
+ next_time = scheduled_time + 60
562
+ sleep_time = next_time - t
563
+ sleep(sleep_time)
564
+ kwargs['timestamp'] = scheduled_time
565
+ self._publish(topic, (), kwargs, True, DEFAULT_MQ_SPIN_LIMIT, 0.0)
566
+
567
+ def _second_timer_loop(self, topic: Topic):
568
+ """
569
+ Second-aligned timer loop.
570
+
571
+ Args:
572
+ topic: Topic to publish on
573
+ """
574
+ kwargs = {'interval': 1}
575
+
576
+ while self.active:
577
+ t = time()
578
+ scheduled_time = t // 1
579
+ next_time = scheduled_time + 1
580
+ sleep_time = next_time - t
581
+ sleep(sleep_time)
582
+ kwargs['timestamp'] = scheduled_time
583
+ self._publish(topic, (), kwargs, True, DEFAULT_MQ_SPIN_LIMIT, 0.0)
584
+
585
+ def run_timer(self, interval: float, topic: Topic, activate_time: Optional[datetime] = None):
586
+ """
587
+ Run a timer with custom interval (blocking call).
588
+
589
+ Args:
590
+ interval: Interval in seconds
591
+ topic: Topic to publish on
592
+ activate_time: Optional activation time
593
+ """
594
+ if not self.active:
595
+ raise RuntimeError('EventEngine must be started before getting timer!')
596
+ self._timer_loop(interval, topic, activate_time)
597
+
598
+ def minute_timer(self, topic: Topic):
599
+ """
600
+ Run minute-aligned timer (blocking call).
601
+
602
+ Args:
603
+ topic: Topic to publish on
604
+ """
605
+ if not self.active:
606
+ raise RuntimeError('EventEngine must be started before getting timer!')
607
+ self._minute_timer_loop(topic)
608
+
609
+ def second_timer(self, topic: Topic):
610
+ """
611
+ Run second-aligned timer (blocking call).
612
+
613
+ Args:
614
+ topic: Topic to publish on
615
+ """
616
+ if not self.active:
617
+ raise RuntimeError('EventEngine must be started before getting timer!')
618
+ self._second_timer_loop(topic)
619
+
620
+ def get_timer(self, interval: float, activate_time: Optional[datetime] = None) -> Topic:
621
+ """
622
+ Get or create a timer with the specified interval.
623
+
624
+ Args:
625
+ interval: Interval in seconds
626
+ activate_time: Optional activation time
627
+
628
+ Returns:
629
+ Topic for the timer
630
+ """
631
+ if not self.active:
632
+ raise RuntimeError('EventEngine must be started before getting timer!')
633
+
634
+ if interval == 1:
635
+ topic = Topic('EventEngine.Internal.Timer.Second')
636
+ timer = Thread(target=self.second_timer, kwargs={'topic': topic})
637
+ elif interval == 60:
638
+ topic = Topic('EventEngine.Internal.Timer.Minute')
639
+ timer = Thread(target=self.minute_timer, kwargs={'topic': topic})
640
+ else:
641
+ topic = Topic.join(['EventEngine', 'Internal', 'Timer', str(interval)])
642
+ timer = Thread(target=self.run_timer,
643
+ kwargs={'interval': interval, 'topic': topic, 'activate_time': activate_time})
644
+
645
+ if interval not in self.timer:
646
+ self.timer[interval] = timer
647
+ timer.start()
648
+ else:
649
+ if activate_time is not None:
650
+ self.logger.debug(
651
+ f'Timer thread with interval [{timedelta(seconds=interval)}] already initialized! '
652
+ f'Argument [activate_time] takes no effect!'
653
+ )
654
+
655
+ return topic
656
+
657
+ def stop(self):
658
+ """Stop the engine and all timers."""
659
+ super().stop()
660
+
661
+ for timer in self.timer.values():
662
+ timer.join()
663
+
664
+ def clear(self):
665
+ """Clear all hooks and timers."""
666
+ super().clear()
667
+
668
+ for t in self.timer.values():
669
+ t.join(timeout=0)
670
+ self.timer.clear()