每隔n秒运行某段代码

218 投票
7 回答
592956 浏览
提问于 2025-04-16 02:14

有没有办法让程序每隔n秒打印一次Hello World!呢?比如说,程序执行完我写的代码后,等5秒(用time.sleep())再执行一次这个代码。我其实是想用这个来更新一个文件,而不是单纯打印Hello World。

举个例子:

startrepeat("print('Hello World')", .01) # Repeats print('Hello World') ever .01 seconds

for i in range(5):
    print(i)

>> Hello World!
>> 0
>> 1
>> 2
>> Hello World!
>> 3
>> Hello World!
>> 4

7 个回答

34

为了避免自己陷入混乱,建议你使用高级Python调度器

这段代码非常简单:

from apscheduler.scheduler import Scheduler

sched = Scheduler()
sched.start()

def some_job():
    print "Every 10 seconds"

sched.add_interval_job(some_job, seconds = 10)

....
sched.shutdown()
158

这是我对这个话题的一个简单看法,基于Alex Martelli的回答,加入了开始和停止的控制:

from threading import Timer

class RepeatedTimer(object):
    def __init__(self, interval, function, *args, **kwargs):
        self._timer     = None
        self.interval   = interval
        self.function   = function
        self.args       = args
        self.kwargs     = kwargs
        self.is_running = False
        self.start()
    
    def _run(self):
        self.is_running = False
        self.start()
        self.function(*self.args, **self.kwargs)
    
    def start(self):
        if not self.is_running:
            self._timer = Timer(self.interval, self._run)
            self._timer.start()
            self.is_running = True
    
    def stop(self):
        self._timer.cancel()
        self.is_running = False

使用方法:

from time import sleep

def hello(name):
    print "Hello %s!" % name

print "starting..."
rt = RepeatedTimer(1, hello, "World") # it auto-starts, no need of rt.start()
try:
    sleep(5) # your long-running job goes here...
finally:
    rt.stop() # better in a try/finally block to make sure the program ends!

特点:

  • 只使用标准库,没有外部依赖
  • start()stop()可以多次安全调用,即使计时器已经开始或停止
  • 要调用的函数可以有位置参数和命名参数
  • 你可以随时更改interval,下次运行时会生效。argskwargs甚至function也是一样!
440
import threading

def printit():
  threading.Timer(5.0, printit).start()
  print "Hello, World!"

printit()

# continue with the rest of your code

这是一个链接,指向Python的官方文档,专门讲解线程中的定时器对象。你可以通过这个链接了解如何在Python中使用定时器来执行一些延迟的任务。

撰写回答