Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking network availability continuously while rest of code is running separately

Tags:

python

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?

like image 732
user2460869 Avatar asked Dec 05 '25 05:12

user2460869


2 Answers

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.

like image 141
Karthikeyan Avatar answered Dec 07 '25 18:12

Karthikeyan


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
like image 26
comepradz Avatar answered Dec 07 '25 18:12

comepradz