龙空技术网

DAY4-step13 Python 延时函数sleep()

易小盟办公设备企业店 123

前言:

如今咱们对“python 延迟1分钟程序”都比较重视,你们都需要了解一些“python 延迟1分钟程序”的相关资讯。那么小编同时在网上网罗了一些对于“python 延迟1分钟程序””的相关文章,希望姐妹们能喜欢,小伙伴们一起来了解一下吧!

什么是Python Sleep?

Python sleep()函数会将延迟代码的执行。 sleep()是time模块的一部分。

语法

import timetime.sleep(seconds)

参数:

seconds:您希望停止执行代码的秒数。

示例:在Python中使用sleep()函数

第1步:

import time

步骤2:

time.sleep(5)
import timeprint("Welcome to guru99 Python Tutorials")time.sleep(5)print("This message will be printed after a wait of 5 seconds")

输出

Welcome to guru99 Python TutorialsThis message will be printed after a wait of 5 seconds#因为延时,这一行在5秒后才会打印出来
如何使用sleep()延迟执行功能?

示例

import timeprint('Code Execution Started')def display():    print('Welcome to Guru99 Tutorials')    time.sleep(5)display()print('Function Execution Delayed')

输出

Code Execution StartedWelcome to Guru99 TutorialsFunction Execution Delayed
display()函数将显示一条消息“ Welcome to Guru99 Tutorials”。 sleep()将在此处暂停指定的秒数,稍后将结束执行display()函数,并打印'Function Execution Delayed'。在Python脚本中添加延迟有哪些不同的方法?

使用sleep()函数

import timemy_message = "Guru99"for i in my_message:   print(i)   time.sleep(1)

输出

Guru99

asyncio.sleep异步线程函数中延时(Python 3.4或更高版本)

您可以在python 3.4及更高版本中使用asyncio.sleep。

如下例所示:

import asyncioprint('Code Execution Started')async def display():    await asyncio.sleep(5)    print('Welcome to Guru99 Tutorials')asyncio.run(display())

Output:

Code Execution StartedWelcome to Guru99 Tutorials
asyncio.run开始一个新线程来异步执行display()函数函数display(),它显示一条消息“ Welcome to Guru99 tutorials”。 async和await是两个关键字。 在函数定义的开头添加async关键字,并在asyncio.sleep()之前添加await。 关键字async / await均用于处理异步任务。当调用函数display()并遇到asyncio.sleep(5)时,代码将在该点处睡眠或暂停5秒钟,完成后将打印该消息。

使用Event().wait(一般用于多线程)

Event().wait方法来自线程模块。 Event.wait()方法将停止任何进程的执行,等待指定的秒数:

from threading import Eventprint('Code Execution Started')def display():    print('Welcome to Guru99 Tutorials')Event().wait(5) display()

输出

Code Execution StartedWelcome to Guru99 Tutorials
该代码使用Event().wait(5)。 5秒钟后,将调用函数display(),并将消息打印在终端内部。

使用计时器

计时器是线程处理中可用的另一种方法,它有助于获得与sleep相同的功能。

from threading import Timerprint('Code Execution Started')def display():    print('Welcome to Guru99 Tutorials')t = Timer(5, display)  t.start()

输出

Code Execution StartedWelcome to Guru99 Tutorials
计时器的参数包括延迟的时间(以秒为单位)以及时钟到时,需要执行的任务。 要使计时器正常工作,您需要调用start()方法。 在代码中Timer 第一个参数是5秒,5秒后会调用display函数。 当调用t.start()时,计时器将开始工作。

标签: #python 延迟1分钟程序