每n秒运行某个代码[重复]

时间:2023-01-18 01:08:56

This question already has an answer here:

这个问题已经有了答案:

Is there a way to, for example, print Hello World! every n seconds? For example, the program would go through whatever code I had, then once it had been 5 seconds (with time.sleep()) it would execute that code. I would be using this to update a file though, not print Hello World.

有没有办法,比如打印Hello World!每n秒?例如,程序将遍历我所拥有的任何代码,然后在5秒之后(使用time.sleep())执行该代码。我将使用它来更新文件,而不是打印Hello World。

For example:

例如:

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 个解决方案

#1


218  

import threading

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

printit()

# continue with the rest of your code

#2


83  

My humble take on the subject, a generalization of Alex Martelli's answer, with start() and stop() control:

我对这个问题的看法很简单,这是Alex Martelli的回答,开始()和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

Usage:

用法:

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!

Features:

特点:

  • Standard library only, no external dependencies
  • 只有标准库,没有外部依赖
  • start() and stop() are safe to call multiple times even if the timer has already started/stopped
  • start()和stop()可以安全地调用多次,即使计时器已经启动/停止。
  • function to be called can have positional and named arguments
  • 要调用的函数可以有位置参数和命名参数
  • You can change interval anytime, it will be effective after next run. Same for args, kwargs and even function!
  • 您可以随时更改间隔,下次运行后将有效。对args, kwargs甚至函数都是一样的!

#3


23  

Save yourself a schizophrenic episode and use the Advanced Python scheduler: http://pythonhosted.org/APScheduler

保存一个精神分裂的片段,使用高级Python调度器:http://pythonhosted.org/APScheduler

The code is so simple:

代码非常简单:

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

#4


17  

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

That'll run as a function. The while True: makes it run forever. You can always take it out of the function if you need.

它会作为一个函数运行。而真实:让它永远运行。如果需要的话,可以把它从函数中去掉。

#5


9  

Here is a simple example compatible with APScheduler 3.00+:

下面是一个与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()

Alternatively, you can use the following. Unlike many of the alternatives, this timer will execute the desired code every n seconds exactly (irrespective of the time it takes for the code to execute). So this is a great option if you cannot afford any drift.

或者,您可以使用以下命令。与许多替代方案不同,这个计时器将精确地每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()

#6


4  

Here's a version that doesn't create a new thread every n seconds:

这里有一个版本不是每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

The event is used to stop the repetitions:

事件被用来停止重复:

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

See Improve current implementation of a setInterval python

参见改进setInterval python的当前实现

#7


1  

You can start a separate thread whose sole duty is to count for 5 seconds, update the file, repeat. You wouldn't want this separate thread to interfere with your main thread.

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

#1


218  

import threading

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

printit()

# continue with the rest of your code

#2


83  

My humble take on the subject, a generalization of Alex Martelli's answer, with start() and stop() control:

我对这个问题的看法很简单,这是Alex Martelli的回答,开始()和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

Usage:

用法:

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!

Features:

特点:

  • Standard library only, no external dependencies
  • 只有标准库,没有外部依赖
  • start() and stop() are safe to call multiple times even if the timer has already started/stopped
  • start()和stop()可以安全地调用多次,即使计时器已经启动/停止。
  • function to be called can have positional and named arguments
  • 要调用的函数可以有位置参数和命名参数
  • You can change interval anytime, it will be effective after next run. Same for args, kwargs and even function!
  • 您可以随时更改间隔,下次运行后将有效。对args, kwargs甚至函数都是一样的!

#3


23  

Save yourself a schizophrenic episode and use the Advanced Python scheduler: http://pythonhosted.org/APScheduler

保存一个精神分裂的片段,使用高级Python调度器:http://pythonhosted.org/APScheduler

The code is so simple:

代码非常简单:

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

#4


17  

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

That'll run as a function. The while True: makes it run forever. You can always take it out of the function if you need.

它会作为一个函数运行。而真实:让它永远运行。如果需要的话,可以把它从函数中去掉。

#5


9  

Here is a simple example compatible with APScheduler 3.00+:

下面是一个与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()

Alternatively, you can use the following. Unlike many of the alternatives, this timer will execute the desired code every n seconds exactly (irrespective of the time it takes for the code to execute). So this is a great option if you cannot afford any drift.

或者,您可以使用以下命令。与许多替代方案不同,这个计时器将精确地每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()

#6


4  

Here's a version that doesn't create a new thread every n seconds:

这里有一个版本不是每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

The event is used to stop the repetitions:

事件被用来停止重复:

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

See Improve current implementation of a setInterval python

参见改进setInterval python的当前实现

#7


1  

You can start a separate thread whose sole duty is to count for 5 seconds, update the file, repeat. You wouldn't want this separate thread to interfere with your main thread.

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