Changes to a Gmail notification script
Question: After a long search I've found [this python
script](https://github.com/gevermann/gmail-iphone-
push/blob/master/server/server.py) that does what I need in order to get a
real time notification to my iOS app when a new email arrives. I usually write
in Objective-c and this is the first time I'm dealing with `Python`. Before
I'll try to setup and run the script I'd like to understand it a bit better.

This is the part that I'm not sure about:

    
    
    # Because this is just an example, exit after 8 hours
    time.sleep(8*60*60)
    
    #finally:
    # Clean up.
    idler.stop()
    idler.join()
    M.close()
    # This is important!
    M.logout()
    

My questions:

  1. Should I comment out `time.sleep(8*60*60)` If I want to keep the connection active at all times?

  2. What's the use for the Clean up section? Do I need it if I want to keep the connection?

  3. Why `M.logout()` is important?

The main question that includes all the above is What changes (if any) I need
to do to this script in order for it to function without stoping or timing
out.

Thanks


Answer: The script has started another thread, the actual work is done in this other
thread. For some reason the main thread is left without anything to do, that's
why the author has put the time.sleep(8*60*60) to occupy it for a while.

If you want to keep the connection active at all times you need to uncomment
the `try:`/`finally:`, see bellow.

If you are new to python beware that indentation is used to define blocks of
code. The cleanup part might actually not be useful if you don't plan to stop
the program, but with the `try:`/`finally:` the cleanup code will be executed
even if you stop the program with Ctrl+C.

Not tested:

    
    
    # Had to do this stuff in a try-finally, since some testing 
    # went a little wrong.....
    try:
        # Set the following two lines to your creds and server
        M = imaplib2.IMAP4_SSL("imap.gmail.com")
        M.login(USER, PASSWORD)
        # We need to get out of the AUTH state, so we just select 
        # the INBOX.
        M.select("INBOX")
        numUnseen = getUnseen()
        sendPushNotification(numUnseen)
    
        #print M.status("INBOX", '(UNSEEN)')
        # Start the Idler thread
        idler = Idler(M)
        idler.start()
    
        # Sleep forever, one minute at a time
        while True:
            time.sleep(60)
    
    finally:
        # Clean up.
        idler.stop()
        idler.join()
        M.close()
        # This is important!
        M.logout()
    

