Python实现定时任务
作者:白熊花田 时间:2022-06-12 04:53:31
Python下实现定时任务的方式有很多种方式。下面介绍几种
循环sleep:
这是一种最简单的方式,在循环里放入要执行的任务,然后sleep一段时间再执行。缺点是,不容易控制,而且sleep是个阻塞函数。
def timer(n):
'''''
每n秒执行一次
'''
while True:
print time.strftime('%Y-%m-%d %X',time.localtime())
yourTask() # 此处为要执行的任务
time.sleep(n)
threading的Timer:
threading模块中的Timer能够帮助实现定时任务,而且是非阻塞的。
比如3秒后打印helloworld:
def printHello():
print "hello world"
Timer(3, printHello).start()
比如每3秒打印一次helloworld:
def printHello():
print "Hello World"
t = Timer(2, printHello)
t.start()
if __name__ == "__main__":
printHello()
使用sched模块:
sched是一种调度(延时处理机制)。
# -*- coding:utf-8 -*-
# use sched to timing
import time
import os
import sched
# 初始化sched模块的scheduler类
# 第一个参数是一个可以返回时间戳的函数,第二个参数可以在定时未到达之前阻塞。
schedule = sched.scheduler(time.time, time.sleep)
# 被周期性调度触发的函数
def execute_command(cmd, inc):
'''''
终端上显示当前计算机的连接情况
'''
os.system(cmd)
schedule.enter(inc, 0, execute_command, (cmd, inc))
def main(cmd, inc=60):
# enter四个参数分别为:间隔事件、优先级(用于同时间到达的两个事件同时执行时定序)、被调用触发的函数,
# 给该触发函数的参数(tuple形式)
schedule.enter(0, 0, execute_command, (cmd, inc))
schedule.run()
# 每60秒查看下网络连接情况
if __name__ == '__main__':
main("netstat -an", 60)
使用定时框架APScheduler:
APScheduler是基于Quartz的一个Python定时任务框架。提供了基于日期、固定时间间隔以及crontab类型的任务,并且可以持久化任务。
这个现在还没自己尝试过,等过段时间用了再来补充。
使用windows的定时任务:
这里可以将所需要的Python程序打包成exe文件,然后在windows下设置定时执行。
来源:http://blog.csdn.net/whiterbear/article/details/50232637
标签:python,定时
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
详解php中implode explode serialize json msgpack性能对比
2023-09-03 18:00:19
MySQL 数据编码 latin1 转 UTF8
2010-10-14 14:20:00
JS实现淘宝支付宝网站的控制台菜单效果
2023-07-22 22:26:12
![](https://img.aspxhome.com/file/2023/1/55941_0s.png)
JavaScript Length 字符长度函数
2008-12-12 12:29:00
通过Turtle库在Python中绘制一个鼠年福鼠
2021-03-01 03:48:12
![](https://img.aspxhome.com/file/2023/2/69462_0s.gif)
Python selenium 三种等待方式详解(必会)
2021-03-13 16:03:33
详解Python编程中基本的数学计算使用
2022-12-12 13:52:04
如何使用PHP计算上一个月的今天
2023-11-15 14:16:25
php比较多维数组中值的大小排序实现代码
2023-11-24 13:22:32
python目标检测给图画框,bbox画到图上并保存案例
2023-03-07 07:47:52
两种与SQL Server数据库交换数据的方法
2008-12-10 15:39:00
opencv实现车牌识别
2023-08-10 01:59:38
Python爬虫之用Xpath获取关键标签实现自动评论盖楼抽奖(二)
2021-02-11 00:58:03
![](https://img.aspxhome.com/file/2023/2/72082_0s.png)
Python实现从url中提取域名的几种方法
2022-03-14 12:55:30
用JavaScript脚本实现的图灵机
2009-01-21 18:10:00
ASP3.0中的流控制能力
2008-10-19 17:41:00
对Python w和w+权限的区别详解
2022-11-30 09:40:15
python 应用之Pycharm 新建模板默认添加编码格式-作者-时间等信息【推荐】
2023-07-09 01:15:42
![](https://img.aspxhome.com/file/2023/1/81621_0s.jpg)
python的内存管理和垃圾回收机制详解
2021-07-30 14:18:05
![](https://img.aspxhome.com/file/2023/5/78845_0s.png)
在pandas多重索引multiIndex中选定指定索引的行方法
2023-07-07 22:04:16
![](https://img.aspxhome.com/file/2023/6/62596_0s.jpg)