我在 Windows 上工作。我想foo()每 10 秒执行一次函数。 我该怎么做?
要在 Windows 上的 Python 中每 10 秒重复执行一个函数,您可以使用几种方法。以下是使用threading.Timer、sched或使用 的简单while循环执行此操作的方法time.sleep。
threading.Timer
sched
while
time.sleep
该threading.Timer课程是
import threading def foo(): print("Function executed") def schedule_function(): foo() # Schedule the next execution after 10 seconds threading.Timer( t 10, schedule_function).start() # Start the first call schedule_function() schedule_functi s
模块sched
import sched import time def foo(): print("Function executed") scheduler = sched.scheduler(time.time, time.sleep) scheduler = sched.scheduler(time.time, time.sleep) scheduler = sched.scheduler(time.time, time scheduler = sched.scheduler(t scheduler = sch sched def schedule_function(sc): foo() f # Schedule the function to be called every 10 seconds sc.enter( sc.enter 10, 1, schedule_function, (sc,)) # Schedule the first call scheduler.enter( scheduler.e sc 10, 1, schedule_function, (scheduler,)) scheduler.run() scheduler. sched
这是一个简单的方法,使用无限循环time.sleep等待
import time def foo(): print("Function executed") whi while True: foo() time.sleep( foo() time.sle foo() tim foo() foo 10)
while True
选择最适合您需求的方法!