Python延时操作实现方法示例
作者:喷跑的豆子 时间:2023-08-25 04:04:50
本文实例讲述了Python延时操作实现方法。分享给大家供大家参考,具体如下:
在日常的开发中,往往会遇到这样的需求,需要某一个函数在一段时间之后才执行以达到某种特定的效果。此时,我们就需要某种机制,使一个函数延后执行。接下来简单介绍一下两种实现此类效果的方法:
sched
import sched,time
def func(a):
print time.time(),"Hello Sched!",a
print time.time()
s = sched.scheduler(time.time,time.sleep)
# 2为延后时间,1为优先级,func为函数名,("test1",)为函数参数
s.enter(2,1,func,("test1",))
s.enter(2,0,func,("test2",))
s.run()
print time.time()
输出结果如下:
1519443179.4
1519443181.4 Hello Sched! test2
1519443181.4 Hello Sched! test1
1519443181.4
从结果可以看出,函数果真延后了2s执行,并且test2比test1先执行,是因为同样是2s后执行,并且test2的优先级比test1高
timer
import threading,time
def func(a):
print time.time(),"Hello Timer!",a
print time.time()
s = threading.Timer(2,func,("test",))
s.start()
print time.time()
输出结果如下:
1519443055.69
1519443055.69
1519443057.69 Hello Timer! test
从结果可以看出,函数果真延后了2s执行。
从两种方式的输出结果可以看出,timer是异步执行的,并不卡住下面代码的执行,而sched会等到执行函数完成后才会往下执行。
希望本文所述对大家Python程序设计有所帮助。
来源:https://blog.csdn.net/y472360651/article/details/79360456
标签:Python,延时操作
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python zip()函数用法实例分析
2022-10-28 21:39:53
FireScope-面向Web开发者和设计者的参考手册
2009-03-22 15:35:00
![](https://img.aspxhome.com/file/UploadPic/20093/22/01_b-44s.jpg)
使用python实现正则匹配检索远端FTP目录下的文件
2022-03-27 07:29:15
SQL Server里书签查找的性能伤害
2024-01-13 08:19:05
![](https://img.aspxhome.com/file/2023/6/106246_0s.png)
MySQL中MIN()函数的使用教程
2024-01-27 21:19:58
高效使用Python字典的清单
2022-05-29 09:53:35
Laravel实现登录跳转功能
2023-06-14 23:35:40
![](https://img.aspxhome.com/file/2023/9/55549_0s.png)
使用Python来开发微信功能
2023-09-25 00:05:28
![](https://img.aspxhome.com/file/2023/5/120275_0s.jpg)
详解Python中的数据清洗工具flashtext
2021-10-05 01:59:47
![](https://img.aspxhome.com/file/2023/5/69645_0s.png)
Python实现将n个点均匀地分布在球面上的方法
2021-02-21 20:56:33
![](https://img.aspxhome.com/file/2023/1/107081_0s.png)
支持python的分布式计算框架Ray详解
2023-06-20 11:34:30
![](https://img.aspxhome.com/file/2023/2/102912_0s.jpg)
Python字符串str超详细详解(适合新手!)
2021-06-26 02:48:00
![](https://img.aspxhome.com/file/2023/0/76060_0s.jpg)
CSS写法性能
2009-05-28 19:09:00
![](https://img.aspxhome.com/file/UploadPic/20095/28/g2009521232840-47s.gif)
python数据结构的排序算法
2021-03-11 04:04:10
![](https://img.aspxhome.com/file/2023/0/78800_0s.png)
python视频按帧截取图片工具
2021-09-08 10:30:56
在windows下 1045 access denied for user
2010-03-04 11:44:00
python类中super()和__init__()的区别
2021-04-17 16:03:02
perl哈希hash的常见用法介绍
2023-08-12 18:46:59
8个js表单验证函数
2007-10-28 19:19:00
python 判断linux进程,并杀死进程的实现方法
2022-06-24 22:31:54