Python Forum
Simple mutli-threaded scheduler using sched - stuck - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Simple mutli-threaded scheduler using sched - stuck (/thread-22420.html)



Simple mutli-threaded scheduler using sched - stuck - Mzarour - Nov-12-2019

Hi there

I need help creating a scheduler that runs indefinitely.
While the scheduler is running users can schedule new events using enter or enterabs.

I’m struggling to do that using a thread or indefinite loop.

Please help


RE: Simple mutli-threaded scheduler using sched - stuck - Larz60+ - Nov-12-2019

I have a basic timer class here. With a simple modification, you can make events recurring, see: https://python-forum.io/Thread-Multi-threaded-Timer-Class?highlight=timer


RE: Simple mutli-threaded scheduler using sched - stuck - Mzarour - Nov-12-2019

Thanks Larz60+ but looking for a simple (i'm new to python) solution which involves the sched library

Here is my attempt so far. My problem is that as soon as scheduler events complete, nothing else runs
import sched
import threading
import time

scheduler = sched.scheduler(time.time, time.sleep)

# Set up a global to be modified by the threads
counter = 0


def increment_counter(name):
    global counter
    print('EVENT:', time.time(), name)
    counter += 1
    print('NOW:', counter)


print('START:', time.time())
e1 = scheduler.enter(5, 1, increment_counter, ('Liverpool match on TV',))
e2 = scheduler.enter(8, 1, increment_counter, ('Take the rubbish bin out',))

def worker():
    print("running worker")
    scheduler.run

# Start a thread to run the events
t = threading.Thread(target=worker, args=())
t.start()

# Back in the main thread, cancel the first scheduled event.
# scheduler.cancel(e1)

while True:
    print("1. Schedule an event")
    print("2. View all scheduled events")
    print("3. Cancel all")
    print("4. Exit")

    choice = int(input("enter option >> "))

    if choice == 1:
        print("Scheduling a new event...")
        e1 = scheduler.enter(3, 1, increment_counter, ('Some event in the future, remind me!',))
    if choice == 2:
        print("Queue status...")
        print(scheduler.queue)
    if choice == 3:
        print("Cancelling all events...")
        for ev in scheduler.queue:
            scheduler.cancel(ev)
    if choice == 4:
        print("Exiting..")
        break

print('FINAL:', counter)