Sample Periodically Invokes Processing in Python Threading.Timer

Asked 2 years ago, Updated 2 years ago, 16 views

I rarely use Python, but when I was looking at my friend's code, I found something strange and found a problem.

http://bty.sakura.ne.jp/wp/archives/71

For example,

import threading

def hello():
    print "hellohelo"

t=threading.Timer(5, hello)
t.start()

There is something like that.Run hello() on another thread after 5 seconds.I understand this.Next, as a sample that repeats processing every certain period of time,

import threading

def hello():
    print "hellohelo"
    t=threading.Timer(1, hello)
    t.start()


t=threading.Thread(target=hello)
t.start()

I feel uncomfortable with this.Hello() contains code to create another thread and run hello() in 5 seconds.If I do this, I think it will generate threads one after another and eventually eat up resources and the program will drop. What do you think?

I'm looking into this and that

http://www.webscalability.com/blog/2016/02/simple-example-of-using-the-threading-timer-class-in-python/

But I'm calling inc in the same way.

I wrote a simple code myself.

import threading
import time

def hello():
    print("Current number of threads:" + str(threading.activeCount())))
    print("[%s]helohelo!!!"%threading.currentThread().getName())
    t=threading.Timer(1, hello)
    t.start()

if__name__=='__main__':
    t=threading.Thread(target=hello)
    t.start()

The results are

Current number of threads: 2
[Thread-1] Hello!
Current number of threads: 2
[Thread-2] Hello!
Current number of threads: 2
[Thread-3] Hello!
Current number of threads: 2
[Thread-4] Hello!
Current number of threads: 2
[Thread-5] Hello!
Current number of threads: 2
[Thread-6] Hello!
Current number of threads: 2
[Thread-7] Hello!

Yes, Thread's name is different every time and a different thread is created, but the number of threads itself has not increased from 2, so is this okay?

Note: It's in the form of a recursive call, but since it's running on a different thread, the parent thread disappears immediately after threading.Timer (1, hello), so this code is stable?This kind of writing might be smarter than the thread generator reboots at the end of the child thread, or the infinite loop + sleep in the thread.

Now that the question is blurred, is it natural for people who are used to Python to run themselves on a different thread at the end?

python

2022-09-30 15:34

2 Answers

Thread count behavior is discarded after t.start() is called in the hello function. You can see that adding infinite looping code after t.start() as mentioned. Also, the thread count remains 2 from Python's main thread.


2022-09-30 15:34

I wrote the following code.

#!/usr/bin/python3

import threading
import time

def hello(thr_no):
  time.sleep(2.5)
  print(thr_no)

def hello1():
  t=threading.Timer(3, hello1)
  t.start()
  hello("hello1")

def hello2():
  while True:
    time.sleep(3)
    hello("hello2")

if__name__=='__main__':
  t1=threading.Thread(target=hello1)
  t1.start()
  t2=threading.Thread(target=hello2)
  t2.start()

hello1() creates threads every 3 seconds, and hello2() holds 3 seconds of sleep in a single thread.As you can see from the execution results, hello2() (Infinite loop), the next execution start will be (timer time + function processing time).However, hello1() is the same as creating a new thread at the end of the function.

In other words, it would be more appropriate to create a different thread at the beginning of a function registered with a timer and start running instead of "running yourself on a different thread at the end" in the sense that the timer functionality is better than infinite loop + sleep.

By the way, you can also create a class that inherits the Timer class in order to invoke processing periodically.I didn't check for multiple runs, so it's incomplete, but please refer to it.

repeated_timer.py

#!/usr/bin/python3

from threading import Timer

class RepeatedTimer (Timer):
  def__init__(self, interval, function, args=[], kwargs={}):
    Timer.__init__(self, interval, self.run, args, kwargs)
    self.thread=None
    self.function=function

  def run(self):
    self.thread=Timer (self.interval, self.run)
    self.thread.start()
    self.function (*self.args, **self.kwargs)

  def cancel(self):
    if self.thread is not None:
      self.thread.cancel()
      self.thread.join()
      del self.thread

if__name__=='__main__':    

  import time

  def hello(message):
    hello.counter+=1
    print(message, hello.counter)
  hello.counter = 0

  t = RepeatedTimer (0.5, hello, ["Hello")
  t.start()
  time.sleep(5)
  t.cancel()
  print("Done.")


2022-09-30 15:34

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.