Python Forum
sched.scheduler -> clean - 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: sched.scheduler -> clean (/thread-14360.html)



sched.scheduler -> clean - denisit - Nov-26-2018

Hi,

I have an issue with sched.scheduler
We need to cancel some upcoming events. (thats working)
but the sched.run()
will wait util the last event was scheduled.

import threading
import sched
import time
import datetime

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

def test():
    print(datetime.datetime.now(),"sleep 6s in main")
    time.sleep(6)
    print(datetime.datetime.now(),"sleep 6s in main Done")
    for x in _schedLed.queue:
       _schedLed.cancel(x)
       print(datetime.datetime.now(),"Cancel:", x)
    print(datetime.datetime.now(),"Cancel DONE")
                   
t = threading.Thread(target=test)
t.start()

_schedLed.enter(5,1,print,("5s"))
_schedLed.enter(20,1,print,("20s"))
_schedLed.run()
print(datetime.datetime.now(),"end")
sudo python3 test3.py
2018-11-26 10:07:13.561110 sleep 6s in main
5 s
2018-11-26 10:07:19.567805 sleep 6s in main Done
2018-11-26 10:07:19.568262 Cancel: Event(time=1543223253.5615287, priority=5, action=<built-in function print>, argument='10s', kwargs={})
2018-11-26 10:07:19.568575 Cancel DONE
2018-11-26 10:07:33.576680 end

Is there a way to fix that?

Regards

(Nov-26-2018, 09:12 AM)denisit Wrote: sudo python3 test3.py
2018-11-26 10:07:13.561110 sleep 6s in main
5 s
2018-11-26 10:07:19.567805 sleep 6s in main Done
2018-11-26 10:07:19.568262 Cancel: Event(time=1543223253.5615287, priority=5, action=<built-in function print>, argument='20s', kwargs={})
2018-11-26 10:07:19.568575 Cancel DONE
2018-11-26 10:07:33.576680 end



RE: sched.scheduler -> clean - Gribouillis - Nov-28-2018

I could make it work by using a custom delay function with a threading.Condition() object
import threading
import sched
import time
import datetime

K = threading.Condition()
def mydelayfunc(secs):
    with K:
        K.wait(timeout=secs)
 
_schedLed = sched.scheduler(time.time, mydelayfunc)
 
def test():
    print(datetime.datetime.now(),"sleep 6s in main")
    time.sleep(6)
    print(datetime.datetime.now(),"sleep 6s in main Done")
    for x in _schedLed.queue:
       _schedLed.cancel(x)
       print(datetime.datetime.now(),"Cancel:", x)
    with K:
        K.notify()
    print(datetime.datetime.now(),"Cancel DONE")
                    
t = threading.Thread(target=test)
t.start()
 
_schedLed.enter(5,1,print,("5s"))
_schedLed.enter(20,1,print,("20s"))
_schedLed.run()
print(datetime.datetime.now(),"end")
The Condition.wait() method is very handy because of its timeout argument and the notify() method. From my experience, it is also quite accurate. You can also do the same with a threading.Event instance (you don't need the with statement then).