简体   繁体   English

每分钟运行一个函数python?

[英]Run a function every minute python?

I want to run a function at the start of every minute, without it lagging over time.我想在每分钟开始时运行一个函数,而不会随着时间的推移而滞后。 Using time.sleep(60) eventually lags.使用 time.sleep(60) 最终会滞后。

while True:
now = datetime.datetime.now().second
if now == 0:
    print(datetime.datetime.now())

The function doesn't take a minute to run so as long as it runs a the beginning it should be fine, I'm not sure if this code is resource-efficient, as its checking every millisecond or so and even if it drifts the if function should correct it.该函数不需要花一分钟的时间运行,所以只要它从一开始就应该没问题,我不确定这段代码是否具有资源效率,因为它每毫秒左右检查一次,即使它漂移如果函数应该纠正它。

Repeat scheduling shouldn't really be done in python, especially by using time.sleep .重复调度不应该真正在 python 中完成,尤其是使用time.sleep The best way would be to get your OS to schedule running the script, using something like cron if you're on Linux or Task Scheduler if you're on Windows最好的方法是让你的操作系统安排运行脚本,如果你在 Linux 上使用 cron 之类的东西,如果你在 Windows 上使用 Task Scheduler

Assuming that you've examined and discarded operating-based solutions such as cron or Windows Scheduled Tasks, what you suggest will work but you're right in that it's CPU intensive.假设您已经检查并放弃了基于操作的解决方案,例如cron或 Windows 计划任务,您的建议起作用,但您是对的,因为它是 CPU 密集型的。 You would be better off sleeping for one second after each check so that:每次检查后最好睡一秒钟,以便:

  1. It's less resource intensive;它的资源密集程度较低; and, more importantly而且,更重要的是
  2. It doesn't execute multiple times per at the start of each minute if the job takes less than a second.如果作业时间少于一秒,它不会在每分钟开始时执行多次

In fact, you could sleep for even longer immediately after the payload by checking how long to the next minute, and use the minute to decide in case the sleep takes you into a second that isn't zero.事实上,您可以通过检查到下一分钟的时间来立即在有效负载之后睡眠更长时间,并使用分钟来决定是否睡眠将您带入不为零的秒。 Something like this may be a good start:像这样的事情可能是一个好的开始:

# Ensure we do it quickly first time.

lastMinute = datetime.datetime.now().minute - 1

# Loop forever.

while True:
    # Get current time, do payload if new minute.

    thisTime = datetime.datetime.now()
    if thisTime.minute != lastMinute:
        doPayload()
        lastMinute = thisTime.minute

        # Try to get close to hh:mm:55 (slow mode).
        # If payload took more than 55s, just go
        # straight to fast mode.

        afterTime = datetime.datetime.now()
        if afterTime.minute == thisTime.minute:
            if afterTime.second < 55:
                time.sleep (55 - afterTime.second)

    # After hh:mm:55, check every second (fast mode).

    time.sleep(1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM