Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import heapq
- import threading
- import time
- def current_time_ms():
- # Return the current time in milliseconds
- return time.time_ns() // 1_000_000
- class Scheduler:
- def __init__(self):
- self.closing = False
- self.jobs = []
- self.cx = threading.Condition() # Initialize the condition object
- self.thread = threading.Thread(target=self.run) # Start the scheduler thread
- self.thread.start()
- def schedule(self, job, delay_ms):
- if self.closing:
- raise ValueError("Scheduler cannot schedule jobs while closing.")
- with self.cx: # Use 'with' statement for acquiring and releasing the lock
- deadline = current_time_ms() + delay_ms
- heapq.heappush(self.jobs, (deadline, job))
- self.cx.notify() # Notify the scheduler thread
- def run(self):
- while not self.closing:
- with self.cx:
- if self.jobs:
- deadline, job = self.jobs[0]
- now = current_time_ms()
- if deadline <= now:
- heapq.heappop(self.jobs)
- job() # Execute the job
- else:
- self.cx.wait((deadline - now) / 1000) # Wait for the next job or a new job
- else:
- self.cx.wait() # Wait indefinitely if there are no jobs
- def close(self):
- with self.cx: # Ensure mutual exclusion for setting 'closing' flag
- self.closing = True
- self.cx.notify() # Wake up the scheduler thread to exit
- self.thread.join() # Wait for the scheduler thread to finish
- def current_time_string(self):
- # Return the current time as a string for logging or debugging
- return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
- def make_job(job_id):
- def job():
- print(f"{Scheduler().current_time_string()}: Executing job {job_id}")
- return job
- if __name__ == '__main__':
- scheduler = Scheduler()
- scheduler.schedule(make_job("A"), 3000) # Schedule job 'A' with a delay of 3000ms
- scheduler.schedule(make_job("B"), 2000) # Adjusted for clarity
- scheduler.schedule(make_job("C"), 10000) # Adjusted for clarity
- time.sleep(15) # Main thread waits before closing the scheduler
- scheduler.close() # Close the scheduler
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement