Created
February 27, 2017 16:21
-
-
Save rhemz/fc682d0db8b97bcd13e1dd8b5dc5b5ab to your computer and use it in GitHub Desktop.
simpl python thread timer example
This file contains 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
from threading import Thread, Event | |
import time | |
import requests | |
class TimerThread(Thread): | |
def __init__(self, event, interval): | |
Thread.__init__(self) | |
self.stopped = event | |
self.interval = interval | |
self.log('Thread created') | |
def run(self): | |
while not self.stopped.wait(self.interval): | |
self.log('ping') | |
def log(self, message): | |
print '{time} ({unixtime}): {msg}'.format(time=time.strftime('%d/%m/%Y %H:%M:%S'), unixtime=int(time.time()), msg=message) | |
def main(): | |
# start the threads | |
stop_flag = Event() | |
thread = TimerThread( | |
event=stop_flag, | |
interval=1 | |
) | |
thread.start() | |
# listen for ctrl+c | |
try: | |
while True: | |
time.sleep(1) | |
pass | |
except (KeyboardInterrupt, SystemExit): | |
print '\n! Received keyboard interrupt, quitting threads.\n' | |
stop_flag.set() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment