Control the python program running for a certain period of time through threads

Source: Internet
Author: User

Control the python program running for a certain period of time through threads

Import time
Class Test (threading. thread): def _ init _ (self, para): # initialize the threading parameter. thread. _ init _ (self) self. para = para def run (self): while (True): doMail (self. para) # collect if _ name _ = "_ main _": para = "" while True: msg = Test (para) msg. setDaemon (True) msg. start () msg. join (2) time. sleep (2)

In the above example, the thread is used for collection, and the thread is started cyclically in the process. The thread is killed every two seconds, and a new thread is restarted for collection.

In python, some thread mechanisms are different from those in C/C ++: in C/C ++, when the main thread ends, its subthreads are killed by the main thread by default. In python, after the main thread ends, the main thread exits after the child thread ends by default.

Python has two functions for thread management: join and setDaemon.

  • Join: If threada. join () is called in thread B, thread B will run threada. join () later after threada is finished.
  • SetDaemon: main thread A starts sub-thread B and calls B. setDaemaon (True): When the main thread ends, the sub-thread B is also killed, which is the same as the default effect in C/C ++.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.