Daily Coding Problem: Problem #10

Photo by AltumCode on Unsplash

Problem

Solution1: Direct implementation

The straightforward approach will be to write a function that takes a function and an integer as arguments, that waits for n milliseconds and then calls the function. Lets implement it then!

import timedef scheduler(f, n):
time.sleep(n)
f()
  1. Multiple functions must be scheduled
  2. Function that take argument must be executed

Solution 2: Multi-threading with list

from time import sleep, timeclass Scheduler:    def __init__(self):
self.functions = []
thread = threading.Thread(target=self._poll)
thread.start()
def _poll(self):
while True:
now = time() * 1000
if len(self.functions) > 0:
due, func, args, kwargs = self.functions[0]
if now > due:
func(*args, **kwargs)
self.functions = [(due, func, args, kwargs) for due, func, args, kwargs in self.functions if due < now]
sleep(0.01)
def schedule(self, func, n, *args, **kwargs):
heapq.heappush(self.functions, (n + time() * 1000, func, args, kwargs))

Solution 3: Multi-threading with min-heap

import heapq
import threading
from time import sleep, timeclass Scheduler: def __init__(self):
self.functions = []
heapq.heapify(self.functions)
thread = threading.Thread(target=self._poll)
thread.start()
def _poll(self):
while True:
now = time() * 1000
if len(self.functions) > 0:
due, func, args, kwargs = self.functions[0]
if now > due:
func(*args, **kwargs)
heapq.heappop(self.functions)
sleep(0.01)
def schedule(self, func, n, *args, **kwargs):
heapq.heappush(self.functions, (n + time() * 1000, func, args, kwargs))

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store