Created
November 25, 2021 05:26
-
-
Save paulgrammer/7cc2a08fd5a622b1aa165cc37147d645 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Python thread pause, resume, exit detail and Example _python | |
https://topic.alibabacloud.com/a/python-thread-pause-resume-exit-detail-and-example-_python_1_29_20095165.html | |
How to start/stop a Python function within a time period (ex. from 10 am to 12:30pm)? | |
https://stackoverflow.com/questions/41289947/how-to-start-stop-a-python-function-within-a-time-period-ex-from-10-am-to-123 | |
""" | |
import threading | |
import time | |
class Job(threading.Thread): | |
def __init__(self, *args, **kwargs): | |
super(Job, self).__init__(*args, **kwargs) | |
self.__flag = threading.Event() # The flag used to pause the thread | |
self.__flag.set() # Set to True | |
self.__running = threading.Event() # Used to stop the thread identification | |
self.__running.set() # Set running to True | |
def run(self): | |
while self.__running.isSet(): | |
self.__flag.wait() # return immediately when it is True, block until the internal flag is True when it is False | |
print(time.time()) | |
time.sleep(1) # By time.sleep(1) you repeat the loop every 1 sec. | |
def pause(self): | |
self.__flag.clear() # Set to False to block the thread | |
def resume(self): | |
self.__flag.set() # Set to True, let the thread stop blocking | |
def stop(self): | |
self.__flag.set() # Resume the thread from the suspended state, if it is already suspended | |
self.__running.clear() # Set to False | |
a = Job() | |
a.start() | |
time.sleep(3) | |
a.pause() | |
time.sleep(3) | |
a.resume() | |
time.sleep(3) | |
a.pause() | |
time.sleep(5) | |
a.stop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment