SafeLoopThread¶
-
class
privex.helpers.thread.
SafeLoopThread
(*args, default_stop=False, default_pause=False, **kwargs)[source]¶ -
__init__
(*args, default_stop=False, default_pause=False, **kwargs)[source] This is a simple loop thread class which uses
StopperThread
to allow an application to signal to the thread that it should shutdown or temporarily pause the loop.Note that if you have a long loop which takes a long time to run, you should regularly check
should_stop
andshould_pause
within your loop, so that the loop can shutdown or pause quickly when you request it to.Example usage:
>>> # Create a sub-class of SafeLoopThread, and implement a loop() method >>> class MyThread(SafeLoopThread): ... loop_sleep = 2 # 'run' will wait this many seconds between each run of your loop(). set to 0 to disable loop sleeps ... def loop(self): ... print("I'm looping!") ... >>> t = MyThread(default_pause=True) >>> t.start() >>> # No output because default_pause was set to True. To start the loop, we'll unpause it >>> t.emit_unpause() I'm looping! I'm looping! I'm looping! >>> t.emit_pause() >>> # We can re-pause the loop from our main thread, and the output stops again. >>> # If we unpause the thread again, we can also ask the thread to stop looping and shutdown using emit_stop >>> t.emit_unpause() I'm looping! I'm looping! >>> t.emit_stop() >>> t.is_alive() False >>> # Because we sent a STOP event, 'run' stopped looping, and returned. >>> # To be able to start the same thread object again, we'd need to clear the STOP event first >>> t.emit_start() # Clear the STOP event we set with emit_stop >>> t.start() # Start the thread again I'm looping! I'm looping!
- Parameters
args –
default_stop – If
True
, will trigger the eventev_stop
in the constructor, which will prevent the thread from being able to start untilev_stop
is cleared e.g. viaemit_start()
default_pause – If
True
, will trigger the eventev_pause
in the constructor, which will cause ‘run’ to wait untilev_pause
is cleared e.g. viaemit_unpause()
before starting the loopkwargs –
- Key List[Union[Event,BetterEvent]] stop_events
Additional
Event
orBetterEvent
‘s which when set, will causeshould_stop
to become True.- Key List[Union[Event,BetterEvent]] pause_events
Additional
Event
orBetterEvent
‘s which when set, will causeshould_pause
to become True.
-
Methods¶
Methods
|
This is a simple loop thread class which uses |
|
|
|
Method representing the thread’s activity. |