每n秒运行特定代码

2024-06-09 15:59:09 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,是否有办法每隔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

Tags: 文件代码程序helloforworldtimesleep
3条回答
import threading

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

printit()

# continue with the rest of your code

https://docs.python.org/3/library/threading.html#timer-objects

我对这个问题的拙见,是亚历克斯·马泰利答案的概括,使用start()和stop()控件:

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都一样!

省去精神分裂症发作,使用高级Python调度程序: http://pythonhosted.org/APScheduler

代码非常简单:

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()

相关问题 更多 >