birddseedd
Posts: 43
Joined: Fri Jan 04, 2019 3:28 pm

code keeps running if i use from threading import timer?

Thu Jan 24, 2019 8:41 pm

seems like my code keeps running if i use this to create a pause. this isn't exactly my goal. I need to "pause" the code for a period of time. but if an "emergency stop" button is pressed during the pause id like to run a final line of code (which stops the machine) and halt all further operation of code.

Code: Select all

########libraries########
import csv
from threading import Timer

########variables########
servo1pos = ''
servo2pos = ''
rtkgpspos = ''
compasspos = ''
delay_in_sec = 5

########Functions########
def countdelay(delay_in_sec):
    print("in function")
    
def yes():
    print("sure is")
    
########Main Code########
print("go")
t = Timer(delay_in_sec, countdelay, [delay_in_sec])  # countdelay function will be called 2 sec later with [delay_in_sec] as *args parameter
t.start()  # returns None
print("done")
print("is other code executing?")
yes()

tempest766
Posts: 105
Joined: Sun Jan 07, 2018 3:44 pm

Re: code keeps running if i use from threading import timer?

Fri Jan 25, 2019 7:19 pm

timers are asynchronous. the program main() will continue to run after you start your timer. an accepted way to pause the main() (in pseudo-code) is as follows, and doesn't use timers

Code: Select all

delay=5seconds
endtime= time() + delay
while (time() < endtime)
	sleep 100ms
you can introduce a timer to the above, and just check a status variable returned when the timer expires as

Code: Select all

bool timerExpired = // status variable set TRUE in timer expiration function
while (not timerExpired)
	sleep 100ms
Understand that how far you overshoot your intended wakeup period will depend on the value of the sleep statement. these methods are relatively platform neutral. more precise methods exist, but are why folks get consulting fees to solve problems

Return to “General discussion”