Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import threading
- class Order:
- def __init__(self, id, dt, **attrs):
- self.id = id
- self.dt = dt
- for k, v in attrs.items():
- setattr(self, k, v)
- self.intervals = iter((10, 10, 10, 20, 100))
- def next_interval(self):
- try:
- return next(self.intervals)
- except StopIteration: return None
- class OrderView:
- def __init__(self, order):
- self.order = order
- def __getattr__(self, attr):
- return getattr(self.order, attr)
- class OrderTransform:
- __transforms = []
- def __init__(self, driver):
- self.driver = driver
- self.transforms = [t(driver) for t in OrderTransform.__transforms if t.driver_match(driver)]
- def do(self, order):
- for t in self.transforms:
- order = t.do(OrderView(order))
- return order
- @staticmethod
- def register(transform):
- OrderTransform.__transforms.append(transform)
- @OrderTransform.register
- class Lazy1:
- def __init__(self, driver):
- self.driver = driver
- @staticmethod
- def driver_match(driver):
- if driver.lazy1: return True
- def do(self, order_view):
- order_view.dt += 3
- return order_view
- @OrderTransform.register
- class Lazy2:
- def __init__(self, driver):
- self.driver = driver
- @staticmethod
- def driver_match(driver):
- if driver.lazy2: return True
- def do(self, order_view):
- order_view.dt += 5
- if self.driver.lazy2 and self.driver.lazy1: return None
- return order_view
- class Driver:
- def __init__(self, id, **attrs):
- self.id = id
- for k, v in attrs.items():
- setattr(self, k, v)
- self.orders = {}
- self.update_transforms()
- def match(self, order):
- new_order = self.transform.do(order)
- if not new_order:
- if order.id in self.orders: self.orders.pop(order.id)
- else:
- self.orders[new_order.id] = new_order
- def update_transforms(self):
- self.transform = OrderTransform(self)
- orders = set()
- drivers = set()
- def init():
- drivers.update({
- Driver(1, lazy1=True, lazy2=False),
- Driver(2, lazy1=False, lazy2=True),
- Driver(3, lazy1=True, lazy2=True),
- }) #откуда то их прочитали
- orders.update({
- Order(1, 10, a1='a1', a2='a2'),
- Order(2, 10, a1='b1', a2='b2'),
- }) #где-то достали
- for o in orders:
- for d in drivers:
- d.match(o)
- def new_order(order):
- #матчим на водителей
- for d in drivers:
- d.match(o)
- #обновляем в списке заказов
- orders.add(order)
- #ставим в очередь на таймер, если есть куда
- next_run = order.next_interval()
- if next_run:
- threading.Timer(next_run, new_order, args=(order,))
- def new_driver(driver):
- for o in orders:
- driver.match(o)
- drivers.add(driver)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement