Let wait_for_internet take a backoff class to control sleeps.
This commit is contained in:
parent
bef06dac75
commit
7a48a7b69c
1 changed files with 16 additions and 3 deletions
|
@ -61,11 +61,22 @@ def has_internet(timeout=2) -> bool:
|
||||||
except socket.error as exc:
|
except socket.error as exc:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def wait_for_internet(timeout) -> None:
|
def wait_for_internet(timeout, *, backoff=None) -> None:
|
||||||
'''
|
'''
|
||||||
This function blocks until an internet connection is available, or the
|
This function blocks until an internet connection is available, or the
|
||||||
timeout is reached.
|
timeout is reached.
|
||||||
|
|
||||||
|
timeout:
|
||||||
|
Number of seconds after which we raise NoInternet.
|
||||||
|
|
||||||
|
backoff:
|
||||||
|
You can provide an instance of a voussoirkit.backoff class to introduce
|
||||||
|
sleeps between each internet check. This can help reduce busywaiting at
|
||||||
|
the expense of not getting the earliest possible return.
|
||||||
|
|
||||||
|
If None, there will be no sleeps between checks, though there is still
|
||||||
|
a timeout on each individual check.
|
||||||
|
|
||||||
Raises NoInternet if the timeout expires.
|
Raises NoInternet if the timeout expires.
|
||||||
'''
|
'''
|
||||||
if timeout <= 0:
|
if timeout <= 0:
|
||||||
|
@ -73,7 +84,9 @@ def wait_for_internet(timeout) -> None:
|
||||||
|
|
||||||
started = time.time()
|
started = time.time()
|
||||||
while True:
|
while True:
|
||||||
|
if has_internet(timeout=2):
|
||||||
|
return
|
||||||
if time.time() - started >= timeout:
|
if time.time() - started >= timeout:
|
||||||
raise NoInternet()
|
raise NoInternet()
|
||||||
if has_internet(timeout=1):
|
if backoff is not None:
|
||||||
return
|
time.sleep(backoff.next())
|
||||||
|
|
Loading…
Reference in a new issue