Arvados-DCO-1.1-Signed-off-by: Radhika Chippada <radhika@curoverse.com>
[arvados.git] / services / nodemanager / arvnodeman / timedcallback.py
1 #!/usr/bin/env python
2 # Copyright (C) The Arvados Authors. All rights reserved.
3 #
4 # SPDX-License-Identifier: AGPL-3.0
5
6 from __future__ import absolute_import, print_function
7
8 import heapq
9 import time
10
11 import pykka
12
13 from .config import actor_class
14
15 class TimedCallBackActor(actor_class):
16     """Send messages to other actors on a schedule.
17
18     Other actors can call the schedule() method to schedule delivery of a
19     message at a later time.  This actor runs the necessary event loop for
20     delivery.
21     """
22     def __init__(self, max_sleep=1):
23         super(TimedCallBackActor, self).__init__()
24         self._proxy = self.actor_ref.tell_proxy()
25         self.messages = []
26         self.max_sleep = max_sleep
27
28     def schedule(self, delivery_time, receiver, *args, **kwargs):
29         if not self.messages:
30             self._proxy.deliver()
31         heapq.heappush(self.messages, (delivery_time, receiver, args, kwargs))
32
33     def deliver(self):
34         if not self.messages:
35             return
36         til_next = self.messages[0][0] - time.time()
37         if til_next <= 0:
38             t, receiver, args, kwargs = heapq.heappop(self.messages)
39             try:
40                 receiver(*args, **kwargs)
41             except pykka.ActorDeadError:
42                 pass
43         else:
44             time.sleep(min(til_next, self.max_sleep))
45         self._proxy.deliver()