每n秒运行一定的代码

时间:2010-08-03 04:40:05

标签: python multithreading

例如,有没有办法每隔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 个答案:

答案 0 :(得分:261)

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

答案 1 :(得分:100)

我对这个主题的谦虚看法,对Alex Martelli答案的概括,以及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
  • 也是如此

答案 2 :(得分:25)

保存自己的精神分裂症情节并使用Advanced 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()

答案 3 :(得分:20)

def update():
    import time
    while True:
        print 'Hello World!'
        time.sleep(5)

这将作为一个功能运行。 while True:使它永远运行。如果需要,您可以随时将其从功能中取出。

答案 4 :(得分:13)

以下是与APScheduler 3.00+兼容的简单示例:

# note that there are many other schedulers available
from apscheduler.schedulers.background import BackgroundScheduler

sched = BackgroundScheduler()

def some_job():
    print('Every 10 seconds')

# seconds can be replaced with minutes, hours, or days
sched.add_job(some_job, 'interval', seconds=10)
sched.start()

...

sched.shutdown()

或者,您可以使用以下内容。与许多替代方案不同,此计时器将每隔 n 秒执行所需的代码(无论代码执行的时间如何)。因此,如果您无法承受任何漂移,这是一个很好的选择。

import time
from threading import Event, Thread

class RepeatedTimer:

    """Repeat `function` every `interval` seconds."""

    def __init__(self, interval, function, *args, **kwargs):
        self.interval = interval
        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.start = time.time()
        self.event = Event()
        self.thread = Thread(target=self._target)
        self.thread.start()

    def _target(self):
        while not self.event.wait(self._time):
            self.function(*self.args, **self.kwargs)

    @property
    def _time(self):
        return self.interval - ((time.time() - self.start) % self.interval)

    def stop(self):
        self.event.set()
        self.thread.join()


# start timer
timer = RepeatedTimer(10, print, 'Hello world')

# stop timer
timer.stop()

答案 5 :(得分:7)

这是一个每n秒无法创建新主题的版本:

from threading import Event, Thread

def call_repeatedly(interval, func, *args):
    stopped = Event()
    def loop():
        while not stopped.wait(interval): # the first call is in `interval` secs
            func(*args)
    Thread(target=loop).start()    
    return stopped.set

该事件用于停止重复:

cancel_future_calls = call_repeatedly(5, print, "Hello, World")
# do something else here...
cancel_future_calls() # stop future calls

请参阅Improve current implementation of a setInterval python

答案 6 :(得分:1)

您可以启动一个单独的线程,其唯一职责是计数5秒,更新文件,重复。你不希望这个单独的线程干扰你的主线程。