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

What are the reasons why Time.Sleep is not recommended for timing?

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces "what are the reasons why it is not recommended to use Time.Sleep to achieve timing function". In daily operation, I believe that many people have doubts about the reasons why they do not recommend using Time.Sleep to achieve timing function. Xiaobian consulted all kinds of data and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubt that "it is not recommended to use Time.Sleep to achieve timing function." Next, please follow the editor to study!

Sometimes we want to implement a very simple timing function, such as having a program call a function at 8 o'clock every morning. But we don't want to install any third-party libraries, and we don't want to use crontab or task scheduling, so we just want to use pure Python.

Some students may write code like this:

Import time import datetime def run (): print ('I am the function that needs to be called every day') def schedule (): target_time = datetime.time (8,0,0) today = datetime.date.today () target_date = today + datetime.timedelta (days=1) target_datetime = datetime.datetime.combine (target_date Target_time) now = datetime.datetime.now () delta = (target_datetime-now). Total_seconds () time.sleep (delta) run () while True: time.sleep (24 * 3600) run () if _ _ name__ = ='_ main__': schedule ()

In this procedure, the first step is to calculate the number of seconds between 8: 00 tomorrow morning and 8: 00 tomorrow morning. After sleeping for so many seconds, run the objective function for the first time. Then enter an endless loop where the program calls the run function every 86400 seconds.

At first glance, there seems to be nothing wrong with the program. But if you observe its running time every day, you will find that as time goes on, the time will become more and more inaccurate.

This is because the run function does not run in an instant. It also takes time to run. Suppose that when the program runs the run function for the first time, it does run exactly 2 seconds. So, after the program sleeps for 86400 seconds, it's actually 8:00:02. From the next day, every day is 2 seconds late. A month will be a minute late.

But in fact, if we pay a trivial price, we can prevent this error from happening, and the program code will become simpler:

Import time import datetime def run (): print ('I am the function that needs to be called every day') def schedule (): last_run = None while True: now = datetime.datetime.now () if now.strftime ('% Hanger% M') = '08def schedule 00' and last_run! = now.date (): run () last_run = now.date () Time.sleep (1) if _ _ name__ = ='_ main__': schedule ()

The program checks every second in an endless loop, and if the current time is exactly 08:00 and the last run was not today, it calls the run function and sets the time of the last run to today. Otherwise, sleep for 1 second.

This is equivalent to checking the time every second, thus avoiding the time error caused by running for a long time. Although it seems that this dead loop will consume a lot of CPU, as long as you do the math, it is actually only 86400 cycles a day. This is not a lot of times.

But in any case, professional things should be done by professional tools. Time.sleep can be used to set periodic intervals, but it is not actually suitable for timing tasks.

Because of a library that supports scheduled tasks, such as Python's schedule or APScheduler, they do a lot of work in ensuring that timing is accurate. Some libraries even use data structures such as time wheels to ensure the accuracy of time. This is not something we can do with two or three lines of Python code.

At this point, the study on "what are the reasons why it is not recommended to use Time.Sleep to achieve timing function" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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