Search code examples
pythonpython-3.xsocketsmultiprocessingserversocket

How to call a function parallelly in a while loop if a condition is met within the loop?


I am creating a socket where the server creates a new log file daily. At midnight, a backup of the previous day's log needs to be taken. The log file is huge and it could take time to compress and upload it on the cloud. I don't want the server to wait until backup is taken before it continues to listen to new incoming requests. I have written pseudo code from the 'if' condition in my code below as I am not sure how to implement it. I am guessing I'll have to use multiprocessing here?

while True:
    clientsocket, address = s.accept()
    enter_log("SUCCESS", "Established incoming connection from {}".format(address))

    if midnight:
        call_another_function_parallelly_for_backup_and_let_the_loop_continue_listening

Solution

  • while True:
        clientsocket, address = s.accept()
        enter_log("SUCCESS", "Established incoming connection from {}".format(address))
    
        if midnight:
            t = threading.Thread(target=your_func, args=(your_arg,))
            t.start()
            t.join()
    
    def your_func(your_arg):
        try:
           your logic
        except Exception as e:
           print(e)
    

    This will create new thread until looping and if is true...