Last active
December 3, 2022 18:35
-
-
Save gkiryaziev/e3810585d41a5356d0bcd2104338e74a to your computer and use it in GitHub Desktop.
Python Non Blocking Delay
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
import time | |
class NonBlockingDelay(): | |
""" Non blocking delay class """ | |
def __init__(self): | |
self._timestamp = 0 | |
self._delay = 0 | |
def timeout(self): | |
""" Check if time is up """ | |
return ((millis() - self._timestamp) > self._delay) | |
def delay_ms(self, delay): | |
""" Non blocking delay in ms """ | |
self._timestamp = millis() | |
self._delay = delay | |
def millis(): | |
""" Get millis """ | |
return int(time.time() * 1000) | |
def delay_ms(delay): | |
""" Blocking delay in ms """ | |
t0 = millis() | |
while (millis() - t0) < delay: | |
pass |
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 delay import NonBlockingDelay, delay_ms, millis | |
# blocking delay (18ms) | |
t0 = millis() | |
delay_ms(18) | |
print(millis() - t0) | |
# non blocking delay | |
d0, d1 = NonBlockingDelay(), NonBlockingDelay() | |
while True: | |
try: | |
if d0.timeout(): | |
print("d0") | |
d0.delay_ms(1000) | |
if d1.timeout(): | |
print("d1") | |
d1.delay_ms(3000) | |
except KeyboardInterrupt: | |
print("Ctrl-C pressed...") | |
exit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment