Python regular tasks to solve the problem in the thread does not automatically exit

Today small for everyone to share a problem-solving task thread timing Python does not automatically exit, a good reference value, we want to help. Come and see, to follow the small series together
python threads have a class called Timer can be used to create a scheduled task, but it can only be run once the problem is, if you want to repeat, you can only call once again in the task timer, but that there is a new problem, that is, after the main process exits, the child thread can not exit normally.

from threading import Timer
  
  
def scheduletaskwrap():
 pritn "in task"
 Timer(10, scheduletaskwrap).start()
  
Timer(10, scheduletaskwrap).start()

Like this above, you can call every 10 seconds a thread, but when you exit the whole program, the child thread

scheduletaskwrap

We continue to perform, to notify it quits how to do?

python threading module provides a lot of ways, what event, wait, lock, etc., these are relatively simple method is not suitable for this kind of trouble timed tasks.

The simplest is to set a global variable, and then determine whether it changed in the thread.

from threading import Timer
gflag=1
  
def scheduletaskwrap():
 global gflag
 pritn "in task"
 if gflag==1:
  Timer(10, scheduletaskwrap).start()
  
Timer(10, scheduletaskwrap).start()

Imagination is wonderful, you will find that the actual run, this will not work, because the main process exits, the global variable, or 1, no change in the child thread, python because there is no exit mechanism for notification of any class.

That there is no other way to do it? On reflection, since the process does not quit notice, but ah class, class destructor generally, can use it to effect a change in a global variable, then added a class, the destructor into the global variable 0, that's it.

class timerexec():
  threadhandle=0
  def __init__(self,thandle): 
    threadhandle=thandle
  def __del__(self): 
    global gflag
    gflag=0
    print u"线程结束",gflag
    threadhandle.cancel
refreshthread=Timer(10, scheduletaskwrap).start()
a=timerexec(refreshthread)

Call timer of the main process in place also like to add code to create the class.

that's it.
We recommend the python learning sites to see how seniors are learning! From basic python script, reptiles, django, data mining, programming techniques, as well as to combat zero-based sorting data items, given to every love learning python small partner! Python veteran day have to explain the timing of technology, to share some of the ways to learn and need to pay attention to small details, click to join our gathering python learner

This problem above Python timing task thread can not automatically exit is small series to share the entire contents of all of the

发布了49 篇原创文章 · 获赞 63 · 访问量 6万+

Guess you like

Origin blog.csdn.net/haoxun05/article/details/104546124