The following python3 code is what I might have expected to generate a few calls to the doit event, followed by a call to the terminate event, which would stop the app, but only the first event fires. What am I doing wrong?
from circuits import Component, Event, Debugger
import time
times = []
class doit(Event):
"""doit Event"""
class terminate(Event):
"""terminate Event"""
class App(Component):
def __init__(self):
super().__init__()
self.interval = .1
self.last = 0
self.count = 0
def doit(self, origin):
times.append(("%s from A at %.03f" % (origin, time.time())))
self.count += 1
self.last = time.time()
def generate_events(self, event):
if self.last + self.interval < time.time():
event.stop()
self.fire(doit('ge'))
if self.count >= 5:
event.stop()
self.fire(terminate())
def terminate(self):
self.stop()
(Debugger() + App()).run()
print("\n".join(times))
I got the same behavior using event.reduce_time_left(0) instead of event.stop().
The main error in the example is that it doesn't reduce_time_left(time.time() - self.last + self.interval) when there is nothing to do.
generate_events fires once when the app starts. Each generator needs to set reduce_time_left() to the maximum reasonable time before firing again - so that it will certainly fire again by that time - whether something is generated or not. Reducing the time to 0 indicates that this cycle is complete (and events need to be fired).
The preferred solution uses Timer to implement the time functionality, reducing this example to the logic to display how it works.
from circuits import BaseComponent, Event, Timer, Debugger, handler
import time
class doit(Event):
"""doit Event"""
class App(BaseComponent):
timer = Timer(.1, doit('A'), persist=True)
def __init__(self):
super().__init__()
self.count = 0
#handler("doit")
def _doit(self, origin):
print("%s from A at %.03f" % (origin, time.time()))
self.count += 1
if self.count > 4:
self.stop()
(App() + Debugger()).run()
Related
How can I start and stop a thread with my poor thread class?
It is in loop, and I want to restart it again at the beginning of the code. How can I do start-stop-restart-stop-restart?
My class:
import threading
class Concur(threading.Thread):
def __init__(self):
self.stopped = False
threading.Thread.__init__(self)
def run(self):
i = 0
while not self.stopped:
time.sleep(1)
i = i + 1
In the main code, I want:
inst = Concur()
while conditon:
inst.start()
# After some operation
inst.stop()
# Some other operation
You can't actually stop and then restart a thread since you can't call its start() method again after its run() method has terminated. However you can make one pause and then later resume its execution by using a threading.Condition variable to avoid concurrency problems when checking or changing its running state.
threading.Condition objects have an associated threading.Lock object and methods to wait for it to be released and will notify any waiting threads when that occurs. Here's an example derived from the code in your question which shows this being done. In the example code I've made the Condition variable a part of Thread subclass instances to better encapsulate the implementation and avoid needing to introduce additional global variables:
from __future__ import print_function
import threading
import time
class Concur(threading.Thread):
def __init__(self):
super(Concur, self).__init__()
self.iterations = 0
self.daemon = True # Allow main to exit even if still running.
self.paused = True # Start out paused.
self.state = threading.Condition()
def run(self):
self.resume()
while True:
with self.state:
if self.paused:
self.state.wait() # Block execution until notified.
# Do stuff...
time.sleep(.1)
self.iterations += 1
def pause(self):
with self.state:
self.paused = True # Block self.
def resume(self):
with self.state:
self.paused = False
self.state.notify() # Unblock self if waiting.
class Stopwatch(object):
""" Simple class to measure elapsed times. """
def start(self):
""" Establish reference point for elapsed time measurements. """
self.start_time = time.time()
return self
#property
def elapsed_time(self):
""" Seconds since started. """
try:
return time.time() - self.start_time
except AttributeError: # Wasn't explicitly started.
self.start_time = time.time()
return 0
MAX_RUN_TIME = 5 # Seconds.
concur = Concur()
stopwatch = Stopwatch()
print('Running for {} seconds...'.format(MAX_RUN_TIME))
concur.start()
while stopwatch.elapsed_time < MAX_RUN_TIME:
concur.resume()
# Can also do other concurrent operations here...
concur.pause()
# Do some other stuff...
# Show Concur thread executed.
print('concur.iterations: {}'.format(concur.iterations))
This is David Heffernan's idea fleshed-out. The example below runs for 1 second, then stops for 1 second, then runs for 1 second, and so on.
import time
import threading
import datetime as DT
import logging
logger = logging.getLogger(__name__)
def worker(cond):
i = 0
while True:
with cond:
cond.wait()
logger.info(i)
time.sleep(0.01)
i += 1
logging.basicConfig(level=logging.DEBUG,
format='[%(asctime)s %(threadName)s] %(message)s',
datefmt='%H:%M:%S')
cond = threading.Condition()
t = threading.Thread(target=worker, args=(cond, ))
t.daemon = True
t.start()
start = DT.datetime.now()
while True:
now = DT.datetime.now()
if (now-start).total_seconds() > 60: break
if now.second % 2:
with cond:
cond.notify()
The implementation of stop() would look like this:
def stop(self):
self.stopped = True
If you want to restart, then you can just create a new instance and start that.
while conditon:
inst = Concur()
inst.start()
#after some operation
inst.stop()
#some other operation
The documentation for Thread makes it clear that the start() method can only be called once for each instance of the class.
If you want to pause and resume a thread, then you'll need to use a condition variable.
how do I invoke an error if the start timer class function is invoke twice ? Thanks
import time
class Timer(object):
def __init__(self):
self._startTime = None
self._endTime = None
def start(self):
self._startTime = time.time() if self._startTime is None else print('Started')
def end(self):
self._endTime = time.time()
print('seconds',self._endTime - self._startTime)
t = Timer()
t.start()
t.start() # should give an error
You can create a instance variable (if you want 1 invocation per class instance) or class variable (only 1 invocation in entire lifecycle as class variable is shared by all instances of class) to keep count of number of invocations and when count exceeds some threshold (In your case it's 1), you can raise an exception. Something like this:
import time
class Timer(object):
def __init__(self):
self._startTime = None
self._endTime = None
self.count = 0 # Instance variable, which allows 1 invocation per instance of this class
def start(self):
self.count+=1
if self.count == 2: # Threshold is 2 here
raise Exception # You custom exception here
self._startTime = time.time() if self._startTime is None else print('Started')
def end(self):
self._endTime = time.time()
print('seconds',self._endTime - self._startTime)
Refer this for more details about class variables vs instance variable in Python.
I have a problem with my code. I'm running this code with thread, then I need to ask about variables SPEED, etc., but I don't know how. I'm still trying to do this, but I'm getting errors with thread.
BTW, I want to make a script that generates fake car data, and I need to fill a database, and then make some diagrams.
import time
import thread
class Test:
def __init__(self):
self.speed = 0
self.dist = 0
self.maxSpeed = 150
self.time = 6
self.fuel = 100
self.distance = 100
self.start = time.time()
self.elapsed = 0
def jazda(self):
while True:
self.speed += 1
if self.speed < self.maxSpeed:
time.sleep(1)
else:
time.sleep(60)
self.elapsed = time.time() - self.start
self.dist = (self.speed * self.elapsed) / 3600
print "Distance: ", self.dist
print "Speed: ", self.speed
print "Time: ", self.elapsed
if self.elapsed > self.time:
break
return 0
def SPEED(self):
return self.speed
and second script:
import test
import thread
import time
class Data:
def __init__(self):
self.test = test.Test()
def get_speed(self):
while True:
return self.test.SPEED()
time.sleep(2)
thread.start_new_thread( test.Test().jazda(), () )
thread.start_new_thread( obdData().get_speed, () )
The error I'm getting is:
thread.start_new_thread( Test().jazda(), () )
TypeError: first arg must be callable
I believe the problem is that the thread.start_new_thread method is expecting a method reference and not a method invocation i.e. test.Test().jazda is a method reference i.e. callable; however, test.Test().jazda() will return the result of the method (0 in this case) not a callable. Your start method should look like thread.start_new_thread(test.Test().jazda, ())
I am trying to write a small audio player in PyQt4. This is a part of the code I've written:
class Player(QMainWindow):
def __init__(self, fileLoc, parent = None):
super(QMainWindow, self).__init__()
self.totTime = 0
self.audioOutput = Phonon.AudioOutput(Phonon.MusicCategory, self)
self.mediaObject = Phonon.MediaObject(self)
self.mediaObject.setTickInterval(1000)
self.mediaObject.tick.connect(self.tick)
self.mediaObject.stateChanged.connect(self.stateChanged)
Phonon.createPath(self.mediaObject, self.audioOutput)
#Define Play, Pause and Stop actions
self.playAction = QAction(self.style().standardIcon(QStyle.SP_MediaPlay),
"Play", self, enabled = False, triggered = self.mediaObject.play)
self.pauseAction = QAction(self.style().standardIcon(QStyle.SP_MediaPause),
"Pause", self, enabled = False, triggered = self.mediaObject.pause)
self.stopAction = QAction(self.style().standardIcon(QStyle.SP_MediaStop),
"Stop", self, enabled = False, triggered = self.mediaObject.stop)
#Initiate User Interface
self.userInterface()
self.timeDisp.display('00:00')
self.mediaObject.setCurrentSource(Phonon.MediaSource(fileLoc))
self.mediaObject.play()
def tick(self, time):
self.displayTime = QTime(0, (time / 60000) % 60, (time / 1000) % 60)
self.timeDisp.display(self.displayTime.toString('mm:ss'))
My problem is, I am unable to figure out how to get the total duration of the file being currently played. I have tried printing the output of mediObject.totalTime() at the end of init(). But it returned -1 for all the videos. mediObject.totalTime() inside tick() is returning incorrect duration (10 - 15 seconds longer than the actual duration).
Also, I may have to access the value of total duration from outside the class. How can I do this?
Thanks in advance.
You could connect the pause, play, and stop actions with other functions:
in the class __init__:
self.total_time = 0
self.playing = False
self.play_action = QAction(self.style().standardIcon((QStyle.SP_MediaPlay),"play",self)
self.play_action.triggered.connect(self.play_triggered_event)
and define the rest of the actions in a similar manner, connecting the triggered field of each QAction to a function
def play_triggered_event(self):
if not self.playing:
self.mediaObject.play
self.playing = True
self.start_time = time.clock()
def pause_triggered_event(self):
if self.playing:
self.mediaObject.pause
self.playing = False
self.total_time += (time.clock() - self.start_time)
def stop_triggered_event(self):
if self.playing:
self.mediaObject.stop
self.playing = False
print "Total time elapsed: " + str(self.total_time)
Basically, it's about saving some program state when the actions that affect the time elapsed are triggered.
To get the total time outside of the class, write an accessor for the class:
def get_total_time(self):
return self.total_time
I am trying to write a method that counts down to a given time and unless a restart command is given, it will execute the task. But I don't think Python threading.Timer class allows for timer to be cancelable.
import threading
def countdown(action):
def printText():
print 'hello!'
t = threading.Timer(5.0, printText)
if (action == 'reset'):
t.cancel()
t.start()
I know the above code is wrong somehow. Would appreciate some kind guidance over here.
You would call the cancel method after you start the timer:
import time
import threading
def hello():
print "hello, world"
time.sleep(2)
t = threading.Timer(3.0, hello)
t.start()
var = 'something'
if var == 'something':
t.cancel()
You might consider using a while-loop on a Thread, instead of using a Timer.
Here is an example appropriated from Nikolaus Gradwohl's answer to another question:
import threading
import time
class TimerClass(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.event = threading.Event()
self.count = 10
def run(self):
while self.count > 0 and not self.event.is_set():
print self.count
self.count -= 1
self.event.wait(1)
def stop(self):
self.event.set()
tmr = TimerClass()
tmr.start()
time.sleep(3)
tmr.stop()
I'm not sure if I understand correctly. Do you want to write something like in this example?
>>> import threading
>>> t = None
>>>
>>> def sayHello():
... global t
... print "Hello!"
... t = threading.Timer(0.5, sayHello)
... t.start()
...
>>> sayHello()
Hello!
Hello!
Hello!
Hello!
Hello!
>>> t.cancel()
>>>
The threading.Timer class does have a cancel method, and although it won't cancel the thread, it will stop the timer from actually firing. What actually happens is that the cancel method sets a threading.Event, and the thread actually executing the threading.Timer will check that event after it's done waiting and before it actually executes the callback.
That said, timers are usually implemented without using a separate thread for each one. The best way to do it depends on what your program is actually doing (while waiting for this timer), but anything with an event loop, like GUI and network frameworks, all have ways to request a timer that is hooked into the eventloop.
Im not sure if best option but for me is woking like this:
t = timer_mgr(.....) append to list "timers.append(t)" and then after all created you can call:
for tm in timers:#threading.enumerate():
print "********", tm.cancel()
my timer_mgr() class is this:
class timer_mgr():
def __init__(self, st, t, hFunction, id, name):
self.is_list = (type(st) is list)
self.st = st
self.t = t
self.id = id
self.hFunction = hFunction
self.thread = threading.Timer(t, self.handle_function, [id])
self.thread.name = name
def handle_function(self, id):
if self.is_list:
print "run_at_time:", datetime.now()
self.hFunction(id)
dt = schedule_fixed_times(datetime.now(), self.st)
print "next:", dt
self.t = (dt-datetime.now()).total_seconds()
else:
self.t = self.st
print "run_every", self.t, datetime.now()
self.hFunction(id)
self.thread = threading.Timer(self.t, self.handle_function, [id])
self.thread.start()
def start(self):
self.thread.start()
def cancel(self):
self.thread.cancel()
Inspired by above post.
Cancelable and Resetting Timer in Python. It uses thread.
Features: Start, Stop, Restart, callback function.
Input: Timeout, sleep_chunk values, and callback_function.
Can use or inherit this class in any other program. Can also pass arguments to the callback function.
Timer should respond in middle also. Not just after completion of full sleep time. So instead of using one full sleep, using small chunks of sleep and kept checking event object in loop.
import threading
import time
class TimerThread(threading.Thread):
def __init__(self, timeout=3, sleep_chunk=0.25, callback=None, *args):
threading.Thread.__init__(self)
self.timeout = timeout
self.sleep_chunk = sleep_chunk
if callback == None:
self.callback = None
else:
self.callback = callback
self.callback_args = args
self.terminate_event = threading.Event()
self.start_event = threading.Event()
self.reset_event = threading.Event()
self.count = self.timeout/self.sleep_chunk
def run(self):
while not self.terminate_event.is_set():
while self.count > 0 and self.start_event.is_set():
# print self.count
# time.sleep(self.sleep_chunk)
# if self.reset_event.is_set():
if self.reset_event.wait(self.sleep_chunk): # wait for a small chunk of timeout
self.reset_event.clear()
self.count = self.timeout/self.sleep_chunk # reset
self.count -= 1
if self.count <= 0:
self.start_event.clear()
#print 'timeout. calling function...'
self.callback(*self.callback_args)
self.count = self.timeout/self.sleep_chunk #reset
def start_timer(self):
self.start_event.set()
def stop_timer(self):
self.start_event.clear()
self.count = self.timeout / self.sleep_chunk # reset
def restart_timer(self):
# reset only if timer is running. otherwise start timer afresh
if self.start_event.is_set():
self.reset_event.set()
else:
self.start_event.set()
def terminate(self):
self.terminate_event.set()
#=================================================================
def my_callback_function():
print 'timeout, do this...'
timeout = 6 # sec
sleep_chunk = .25 # sec
tmr = TimerThread(timeout, sleep_chunk, my_callback_function)
tmr.start()
quit = '0'
while True:
quit = raw_input("Proceed or quit: ")
if quit == 'q':
tmr.terminate()
tmr.join()
break
tmr.start_timer()
if raw_input("Stop ? : ") == 's':
tmr.stop_timer()
if raw_input("Restart ? : ") == 'r':
tmr.restart_timer()