Skip to content

Instantly share code, notes, and snippets.

@simon-hibbs
Last active April 2, 2019 08:36
Show Gist options
  • Save simon-hibbs/e17ff209f233e9019c70258ca5111c0a to your computer and use it in GitHub Desktop.
Save simon-hibbs/e17ff209f233e9019c70258ca5111c0a to your computer and use it in GitHub Desktop.
Pausable, restartable clock
#!/bin/python
import time
import logging
logger = logging.getLogger(__name__)
class Clock(object):
def __init__(self, stopped=False):
self._base = time.time()
logging.info('Clock created. ' + 'Stopped = ' + str(stopped) + ', Base = ' + str(self._base))
self.stopped = stopped
def stop(self):
if not self.stopped:
self.stopped_raw_time = time.time()
logging.info('Clock stopped at ' + str(self.time))
self.stopped = True
else:
logging.warning('Attempt to stop the clock at ' + str(self.time) + ' - Clock already stopped!')
def start(self):
if self.stopped:
logging.info('Clock started at ' + str(self.time))
delta = time.time() - self.stopped_raw_time
self._base += delta
self.stopped = False
else:
logging.warning('Attempted clock start at ' + str(self.time) + ' - Clock already running!')
@property
def time(self):
if self.stopped:
return self.stopped_raw_time - self._base
else:
return time.time() - self._base
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
clock = Clock()
print 'Base = ', clock._base
print clock.time
print 'started, wait 5'
time.sleep(5)
print clock.time, '\n'
clock.stop()
print 'stopped, wait 5'
time.sleep(5)
print clock.time, '\n'
print 'Stopping, but already stopped'
clock.stop()
print 'waiting 3 sec'
time.sleep(3)
print 'after 3 sec - ', clock.time, '\n'
clock.start()
print 'Started, wait 5'
time.sleep(5)
print clock.time, '\n'
print 'Starting, but already started'
clock.start()
print 'waiting 3 sec'
time.sleep(3)
print 'After 3 -', clock.time
@simon-hibbs
Copy link
Author

simon-hibbs commented Apr 2, 2019

A class implementing a clock that can be stopped and started again. Now includes warnings on attempts to stop the clock if it's already stopped, or to start it if it's already running.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment