Search code examples
pythonloopswhile-loopirc

Two while loops at one?


I'm making an IRC bot in Python. There's a while loop that repeats each time data is received from the IRC server. I want to have another while loop that runs every minute, so there's no way that I can think of to combine the loops.

Is there a way to "background" one of the loops and allow the rest of the program to keep running while it "does its thing"?


Solution

  • This simple example ought to get you started, In this case there are two while loops and time.sleep(seconds) is used to mimic some work

    import threading
    import time
    
    def func_1():
        i = 0
        while i<5:
            i += 1
            time.sleep(1.5) # Do some work for 1.5 seconds
            print 'func_1'
    
    def func_2():
        i = 0
        while i<5:
            i += 1
            time.sleep(0.5) # Do some work for 0.5 seconds
            print 'func_2'
    
    thread1 = threading.Thread(target=func_1)
    thread1.start()
    thread2 = threading.Thread(target=func_2)
    thread2.start()
    

    Produces:

    func_2 #0.5 seconds elapsed
    func_2 #1.0 seconds elapsed
    func_1 #1.5 seconds elapsed finally func_1 :)
    func_2 #1.5 threading is not mutithreading! ;)
    func_2 #2.0 seconds elapsed
    func_2 #2.5 seconds elapsed and since variable i is 5 func_2 is no more :(
    func_1 #3.0 seconds elapsed
    func_1 #4.5 seconds elapsed
    func_1 #6.0 seconds elapsed
    func_1 #7.5 seconds elapsed
    

    Edit:

    What I meant by saying threading is not mutithreading! ;) is that if by any chance you think that both func_1 and func_2 are executed concurrently at 1.5 seconds it is not True as threads run in the same memory space but if you use multiprocessing they have separate memory spaces and would run concurrently

    Finally, For your case you should use threading as its more suitable for these type of tasks