Skip to content

Instantly share code, notes, and snippets.

@rhemz
Created February 27, 2017 16:21
Show Gist options
  • Save rhemz/fc682d0db8b97bcd13e1dd8b5dc5b5ab to your computer and use it in GitHub Desktop.
Save rhemz/fc682d0db8b97bcd13e1dd8b5dc5b5ab to your computer and use it in GitHub Desktop.
simpl python thread timer example
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