Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize simple timer based on Python

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Based on Python how to achieve a simple timer, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can gain something.

The so-called timer refers to the mechanism of performing specific tasks at specific intervals. Almost all programming languages have timer implementation. For example, Java has util.Timer and util.TimerTask,JavaScript, and setInterval and setTimeout, which can implement very complex scheduled task processing. However, it is difficult to understand that the omnipotent Python does not have a decent timer.

Beginner students will certainly say: isn't there a time.sleep? Set the alarm clock to sleep, the alarm clock goes off, get up to work, this is not a timer? Yes, time.sleep has the basic elements of a timer, but if it is used as a timer, it has two fatal defects: one is that the main thread blocks the main thread and cannot do anything while sleeping; the other is that the main thread is required to perform scheduled tasks after waking up-even with threading technology, the main thread has to create child threads first.

At this point, students who are familiar with the threading module threading may say: threading.Timer runs in a threaded way, without blocking the main thread and executing scheduled tasks without the intervention of the main thread. Isn't this a perfect timer?

Let's take a look at how threading.Timer works. The following code demonstrates the basic use of threading.Timer: calling the function do_something as a thread 2 seconds after starting the timer, the main thread can still do other work during the 2 seconds the timer waits, and while the do_something is running-- in this case, reading input from the keyboard to block the main thread in order to observe how the timer works.

Import timeimport threadingdef do_something (name, gender='male'): print (time.time ()), 'timing time is up Perform specific tasks') print ('name:%s, gender:%s'% (name, gender)) timer = threading.Timer (2, do_something, args= (' Alice',), kwargs= {'gender':'female'}) timer.start () print (time.time (),' scheduled start time') input ('press enter to end\ n') # blocking the process here

As expected, two seconds after the timer starts, the function do_something is called, during which time you can press enter to end the program. The running result of this code is as follows.

1627438957.4297626 timing start time

Press enter to end

1627438959.4299397 scheduled time to perform specific tasks

Name:Alice, gender:female

From the effect of use, threading.Timer can be called a simple and easy-to-use timer. However, threading.Timer has an obvious drawback, which is that it does not support continuous scheduled tasks, such as calling the do_something function every 2 seconds. If you must use threading.Timer to achieve continuous timing, you can only use a workaround similar to nesting to start the timer again in the do_something function.

Import timeimport threadingdef do_something (name, gender='male'): global timer timer = threading.Timer (2, do_something, args= (name,), kwargs= {'gender':gender}) timer.start () print (time.time (),' time is up Perform specific tasks') print ('name:%s, gender:%s'% (name, gender)) time.sleep (5) print (time.time (),' complete specific tasks') timer = threading.Timer (2, do_something, args= ('Alice',), kwargs= {' gender':'female'}) timer.start () input ('press enter to end\ n') # blocking the process here

This code redefines the do_something function to start the next scheduled task at the beginning of the function. The reason why it is placed in the starting position is to ensure that the time interval between the two timings is as accurate as possible. Rao is so, the following running results show that the interval between the two timers is about 10 milliseconds more than the designed 2 seconds, and the error is accumulated continuously, repeated 100 times, the error will be more than 1 second.

Press enter to end

1627440628.683803 scheduled time to perform specific tasks

Name:Alice, gender:female

1627440630.6929214 scheduled time to perform specific tasks

Name:Alice, gender:female

1627440632.707388 scheduled time to perform specific tasks

Name:Alice, gender:female

1627440633.6890671 complete specific tasks

1627440634.722474 scheduled time to perform specific tasks

Name:Alice, gender:female

1627440635.7092102 complete specific tasks

1627440636.7277966 scheduled time to perform specific tasks

Name:Alice, gender:female

For continuous scheduled tasks, threading.Timer 's performance is not satisfactory, but this nested writing completely subverts code aesthetics. For programmers who are addicted to code cleanliness like me, it is unacceptable and unacceptable. In my opinion, a perfect timer should meet the following five conditions and have the structure shown in the following figure.

Do not block the main thread

Both single timing and continuous timing are supported.

Perform scheduled tasks in a thread or process manner

The creation and running of the thread or process of the timing task does not affect the timing accuracy.

Timing accuracy is accurate enough, and errors will not accumulate

Since Python doesn't provide a decent timer, write one yourself. The following timer meets the five conditions mentioned above, the minimum time interval can be as low as 10 milliseconds, and the error will not accumulate. Although it is not perfect, it is reasonable in terms of structure and accuracy.

Import timeimport threadingclass PyTimer: "" timer class "" def _ _ init__ (self, func, * args * * kwargs): "constructor" self.func = func self.args = args self.kwargs = kwargs self.running = False def _ run_func (self): "run the timing event function" th = threading.Thread (target=self.func, args=self.args) " Kwargs=self.kwargs) th.setDaemon (True) th.start () def _ start (self, interval Once): "" thread function to start timer "" if interval < 0.010: interval = 0.010 if interval < 0.050: dt = interval/10 else: dt = 0.005 if once: deadline = time.time () + interval While time.time () < deadline: time.sleep (dt) # timing time Call the timing event function self._run_func () else: self.running = True deadline = time.time () + interval while self.running: while time.time () < deadline: time.sleep (dt) # to update the next decision Time deadline + = interval # time is up Call timing event function if self.running: self._run_func () def start (self, interval, once=False): "" start timer interval-fixed time interval, floating point, in seconds, with a maximum precision of 10 milliseconds once-whether to start only once The default is continuous "" th = threading.Thread (target=self._start, args= (interval, once)) th.setDaemon (True) th.start () def stop (self): "" stop timer "" self.running = False "

When the timer class PyTimer is instantiated, the timing task function needs to be passed in. If the scheduled task function has parameters, it can also be provided in the order of location parameters and keyword parameters. PyTimer timers provide two methods, start and stop, to start and stop timers. The stop method does not need parameters, while start needs a fixed time interval parameter in seconds. Start also has a Boolean default parameter once, which can be set for single timing. The default value of the once parameter is False, that is, the default continuous timing; if you need a single timer, you only need to set once to true.

Def do_something (name, gender='male'): print (time.time ()), 'timing time is up Perform specific tasks') print ('name:%s, gender:%s'% (name, gender)) time.sleep (5) print (time.time (),' complete specific tasks') timer = PyTimer (do_something, 'Alice', gender='female') timer.start (0.5, once=False) input (' press enter to end\ n') # here block the process timer.stop ()

The above is an example of using a PyTimer timer to call the function do_something continuously at an interval of half a second. The running result of this code is as follows.

Press enter to end

1627450313.425347 scheduled time to perform specific tasks

Name:Alice, gender:female

1627450313.9226055 scheduled time to perform specific tasks

Name:Alice, gender:female

1627450314.421761 scheduled time to perform specific tasks

Name:Alice, gender:female

1627450314.9243422 scheduled time to perform specific tasks

Name:Alice, gender:female

1627450315.422722 scheduled time to perform specific tasks

Name:Alice, gender:female

1627450315.9200313 scheduled time to perform specific tasks

Name:Alice, gender:female

1627450316.4204514 scheduled time to perform specific tasks

Name:Alice, gender:female

1627450316.9215539 scheduled time to perform specific tasks

Name:Alice, gender:female

1627450317.4228196 scheduled time to perform specific tasks

Name:Alice, gender:female

1627450317.9245899 scheduled time to perform specific tasks

Name:Alice, gender:female

1627450318.42355 scheduled time to perform specific tasks

Name:Alice, gender:female

1627450318.4393418 complete specific tasks

1627450318.9251466 scheduled time to perform specific tasks

Name:Alice, gender:female

1627450318.9395308 complete specific tasks

1627450319.4242043 complete specific tasks

1627450319.4242043 scheduled time to perform specific tasks

Name:Alice, gender:female

1627450319.9253905 scheduled time to perform specific tasks

Name:Alice, gender:female

1627450319.9411068 complete specific tasks

1627450320.425871 complete specific tasks

1627450320.425871 scheduled time to perform specific tasks

Name:Alice, gender:female

Although each timed task takes 5 seconds to run, a new thread is started on time to run the timed task every 0.5 seconds. It can be seen from the records that although the start-up time of each scheduled task has an error of several milliseconds, the error does not accumulate, and the average interval between repeated execution is always stable at 0.5 seconds.

Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report