2022年 11月 7日

python中延时函数_python – 如何在Python中延迟时间?

我想知道如何在Python脚本中加时间延迟。

importtime

time.sleep(5) # Delays for 5 seconds. You can also use a float value.

这是另一个例子,大约每分钟运行一次:

importtimewhile True:

print(“This prints once a minute.”)time.sleep(60) # Delay for 1 minute (60 seconds).

您可以sleep()在时间模块中使用该功能。它可以采用浮动参数进行亚秒级分辨率。

fromtimeimportsleep

sleep(0.1) # Time in seconds.

在时间模块中尝试睡眠功能。

importtime

time.sleep(60)

并把它放在一个while循环中,一个语句只会在一分钟内执行…这允许你以预定义的间隔运行一个语句,无论命令花了多长时间(只要它花费不到一分钟或5或60或无论你把它设置为什么)例如,我想每分钟运行一次ping。如果我仅仅time.sleep(60)或time.sleep(45) 甚至,平安不会总是相同的时间量。这是代码:)

time.sleep(time.localtime(time.time())[5])

在[5]刚刚拉秒的的time.localtime()的返回值。

最棒的time.sleep是它支持浮点数!

importtime

time.sleep(0.1)

你可以通过简单地做到这一点:

fromtimeimportsleep# Doing stuffsleep(0.5) # Sleeping half a second (sleep() uses seconds, but you can also use floats)

# Doing stuff…

一个沉睡的发电机有点乐趣。

问题是时间延迟。它可以是固定的时间,但在某些情况下,我们可能需要从上次开始测量延迟。这是一个可能的解决方案:

自上次以来测量的延迟(定期醒来)

这种情况可能是,我们希望尽可能经常地做一些事情,我们不希望与所有的打扰last_time,next_time东西各地的我们的代码。

蜂鸣器发生器

以下代码(sleepy.py)定义了一个buzzergen生成器:

importtimefromitertoolsimportcountdefbuzzergen(period):nexttime=time.time() +periodforiincount():now=time.time()tosleep=nexttime-nowiftosleep> 0:time.sleep(tosleep)nexttime+=periodelse:nexttime=now+periodyieldi,nexttime

调用常规的buzzergen

fromsleepyimportbuzzergenimporttime

buzzer=buzzergen(3) # Planning to wake up each 3 seconds

printtime.time()buzzer.next()

printtime.time()time.sleep(2)buzzer.next()

printtime.time()time.sleep(5) # Sleeping a bit longer than usuallybuzzer.next()

printtime.time()buzzer.next()

printtime.time()

运行它我们看到:

1400102636.46

1400102639.46

1400102642.46

1400102647.47

1400102650.47

我们也可以直接在循环中使用它:

importrandomforringinbuzzergen(3):

print “now”,time.time()

print “ring”,ring

time.sleep(random.choice([0, 2, 4, 6]))

运行它我们可能会看到:

now1400102751.46ring(0, 1400102754.461676)now1400102754.46ring(1, 1400102757.461676)now1400102757.46ring(2, 1400102760.461676)now1400102760.46ring(3, 1400102763.461676)now1400102766.47ring(4, 1400102769.47115)now1400102769.47ring(5, 1400102772.47115)now1400102772.47ring(6, 1400102775.47115)now1400102775.47ring(7, 1400102778.47115)

正如我们所看到的,这种蜂鸣器不会过于僵硬,即使我们睡过头而且不按规定时间安排,也能让我们赶上常规的困倦时间间隔。

如何在Python中延迟时间?

在一个线程中我建议睡眠功能:

>>> fromtimeimportsleep>>>sleep(4)

这实际上暂停了操作系统调用它的线程的处理,允许其他线程和进程在休眠时执行。

将其用于此目的,或仅仅是为了延迟执行某个功能。例如:

>>> defparty_time():

… print(‘hooray!’)

>>>sleep(3);party_time()hooray!

“万岁!” 我打了3秒后打印出来Enter。

使用sleep多个线程和进程的示例

再次,sleep暂停你的线程 – 它使用零处理能力。

为了演示,创建一个这样的脚本(我首先在交互式Python 3.5 shell中尝试过这个,但子进程party_later由于某种原因找不到该函数):

fromconcurrent.futuresimport ThreadPoolExecutor, ProcessPoolExecutor,as_completedfromtimeimportsleep,timedefparty_later(kind=”,n=”):sleep(3)

returnkind+n+ ‘ party time!: ‘ +__name__defmain():

with ProcessPoolExecutor() asproc_executor:

with ThreadPoolExecutor() asthread_executor:start_time=time()proc_future1=proc_executor.submit(party_later,kind=’proc’,n=’1′)proc_future2=proc_executor.submit(party_later,kind=’proc’,n=’2′)thread_future1=thread_executor.submit(party_later,kind=’thread’,n=’1′)thread_future2=thread_executor.submit(party_later,kind=’thread’,n=’2′)

forfinas_completed([proc_future1,proc_future2,thread_future1,thread_future2,]):

print(f.result())end_time=time()

print(‘total time to execute four 3-sec functions:’,end_time-start_time)

if__name__== ‘__main__’:main()

此脚本的示例输出:

thread1 party time!:__main__

thread2 party time!:__main__

proc1 party time!:__mp_main__

proc2 party time!:__mp_main__

total time to execute four3-sec functions: 3.4519670009613037

多线程

您可以使用Timer线程对象触发稍后在单独线程中调用的函数:

>>> fromthreadingimport Timer

>>>t= Timer(3,party_time,args=None,kwargs=None)

>>>t.start()

>>>

>>>hooray!

>>>

空白行说明该功能打印到我的标准输出,我不得不点击Enter以确保我在提示。

这个方法的好处是,当Timer线程在等待时,我能够做其他事情,在这种情况下,击中Enter一次 – 在函数执行之前(参见第一个空提示)。

多处理库中没有相应的对象。你可以创建一个,但它可能不存在是有原因的。对于简单的计时器而言,子线程比整个新的子进程更有意义。