如何每n秒运行一个耗时的过程?

How to run a time consuming process every n seconds?

我需要每 n 秒 运行 一个进程。我认为 Threading.timer 是最好的方法。但是,当我 运行 我的命令时,它不会每 n 秒 运行,而是一遍又一遍地开始 运行ning,所用时间比给定的 n 少得多,并且循环不可阻挡。这是我的代码:

#!/usr/bin/python

import threading
import time

brake = 10
k = int(5)

def printit():
    for x in range(k):
        threading.Timer((int(brake)), printit).start()
        print "Hello World!"  
        #i have a longer process here, it takes a few seconds to run
        #i give more than double of the time needed to run it
printit()

所以我想要发生的是:它打印 Hello world 5 次,每次之间间隔 10 秒。但是相反,它打印得更快并且不会停止。 我是否遗漏了一些参数,或者我正在尝试 运行 的过程有问题?我也很欣赏任何其他更简单的方法 运行 每 n 秒处理一次。

您只需在 python

中使用 time 即可
import time

k = int(5)

def printit():
    for x in range(k):
        time.sleep(5)
        print "Hello World!"
        #i have a longer process here, it takes a few seconds to run
        #i give more than double of the time needed to run it
printit()

你真的想暂停 10 秒。

time.sleep(brake)

如果您确实想要一个计时器方法来 运行 在单独的线程中执行所有操作。您需要将打印功能与计时器功能分开。但是,这将在 10 秒后同时打印 "Hello World!" 5 次。

import threading
import time

brake = 10
k = 5

def printit():
    for x in range(k):
        threading.Timer(brake, long_process, args=('Hello World!',)).start()

def long_process(item):
    print(item)
    #i have a longer process here, it takes a few seconds to run
    #i give more than double of the time needed to run it


printit()

虽然您似乎正在使用 python2.x(打印为关键字),因此睡眠是个好主意,但如果您使用的是 py3.4 以上版本,则有 asyncio

import asyncio

def do_task(end_time, loop):
    print('hello world!')
    if (loop.time() + 1.0) < end_time:
        loop.call_later(1, do_task, end_time, loop)
    else:
        loop.stop()

loop = asyncio.get_event_loop()

end_time = loop.time() + 10.0
loop.call_soon(do_task, end_time, loop)

loop.run_forever()
loop.close()

感谢所有的回答,但与此同时我想出了一个完美的方法:

import time

a=2
b=5

for x in range(a):
    start = time.time()
    print "Hello World!"
    time.sleep(3)
    run = (-(start)+time.time())
    time.sleep(int(b)-(run))

这是我知道的唯一方法 运行 每 n 秒重复一个过程。只需使用 time.sleep 就可以轻松完成很多工作,但如果您的进程较长,则需要在进程达到 运行.

时减少休眠时间