I am writing a code in Python to design a software application. I want to add following functionality in my code:
When user starts using software, a ping() function runs and tries to connect to internet to fetch some data. If network is not available then it should continuously check network availability to fetch the data. While that ping() is checking network continuously, I want my software application to do usual things.
My code is:
def ping():
global lst1
if network_connection() is True:
links = lxml.html.parse("http://google.com").xpath("//a/@href")
for url in links:
lst1.append(url)
else:
ping()
def network_connection():
network=False
try:
response = urllib2.urlopen("http://google.com", None, 2.5)
network=True
except urllib2.URLError, e:
pass
return network
When application starts I call ping() and inside ping() function I am doing a recursive call. It is obviously wrong because in that case my code will stuck in this recursive call until network connection is available and application will not be initiated.
Is there anyway that I can do both things side by side: checking network availability and running rest of code at the same time?
First of all, there is no need for continuous pinging, even that happens in a separate process/thread. You should use an exponential backoff algorithm.
And have the pinging process update a shared variable in the event of network failure to make sure your main process waits until the network is up/ or do offline work. For this, your code has to check the variable periodically during execution. I would suggest the multiprocessing module for this task.
You can easily use while loop to constantly check the network availability inside the ping() function. I'm totally agree with Blue Ice's answer about CPU usage when the code continuously check for internet connection. A single time.sleep() call from module time is enough to throttle down the loop.
import time
def ping():
global lst1
status = True
while(status):
if network_connection() is True:
links = lxml.html.parse("http://google.com").xpath("//a/@href")
status = False
for url in links:
lst1.append(url)
else:
time.sleep(0.1) #use 100 milliseconds sleep to throttke down CPU usage
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With