Python: Pass or Sleep for long running processes?

前端 未结 7 1410
情书的邮戳
情书的邮戳 2020-11-30 05:10

I am writing an queue processing application which uses threads for waiting on and responding to queue messages to be delivered to the app. For the main part of the applica

7条回答
  •  情话喂你
    2020-11-30 06:00

    Running a method as a background thread with sleep in Python

        import threading
        import time
    
    
        class ThreadingExample(object):
            """ Threading example class
            The run() method will be started and it will run in the background
            until the application exits.
            """
    
            def __init__(self, interval=1):
                """ Constructor
                :type interval: int
                :param interval: Check interval, in seconds
                """
                self.interval = interval
    
                thread = threading.Thread(target=self.run, args=())
                thread.daemon = True                            # Daemonize thread
                thread.start()                                  # Start the execution
    
            def run(self):
                """ Method that runs forever """
                while True:
                    # Do something
                    print('Doing something imporant in the background')
    
                    time.sleep(self.interval)
    
        example = ThreadingExample()
        time.sleep(3)
        print('Checkpoint')
        time.sleep(2)
        print('Bye')
    

提交回复
热议问题