python通过线程实现定时器timer的方法
作者:chongq 发布时间:2023-04-28 17:49:28
标签:python,线程,定时器
本文实例讲述了python通过线程实现定时器timer的方法。分享给大家供大家参考。具体分析如下:
这个python类实现了一个定时器效果,调用非常简单,可以让系统定时执行指定的函数
下面介绍以threading模块来实现定时器的方法。
使用前先做一个简单试验:
import threading
def sayhello():
print "hello world"
global t #Notice: use global variable!
t = threading.Timer(5.0, sayhello)
t.start()
t = threading.Timer(5.0, sayhello)
t.start()
运行结果如下:
>python hello.py
hello world
hello world
hello world
下面是定时器类的实现:
class Timer(threading.Thread):
"""
very simple but useless timer.
"""
def __init__(self, seconds):
self.runTime = seconds
threading.Thread.__init__(self)
def run(self):
time.sleep(self.runTime)
print "Buzzzz!! Time's up!"
class CountDownTimer(Timer):
"""
a timer that can counts down the seconds.
"""
def run(self):
counter = self.runTime
for sec in range(self.runTime):
print counter
time.sleep(1.0)
counter -= 1
print "Done"
class CountDownExec(CountDownTimer):
"""
a timer that execute an action at the end of the timer run.
"""
def __init__(self, seconds, action, args=[]):
self.args = args
self.action = action
CountDownTimer.__init__(self, seconds)
def run(self):
CountDownTimer.run(self)
self.action(self.args)
def myAction(args=[]):
print "Performing my action with args:"
print args
if __name__ == "__main__":
t = CountDownExec(3, myAction, ["hello", "world"])
t.start()
以上代码在Python 2.5.4中运行通过
希望本文所述对大家的Python程序设计有所帮助。
0
投稿
猜你喜欢
- Oracle当然是世界上最强大的数据库,但它的客户端sqlplus真的不友好,现在还不能支持上下方向键翻查历史命令,这里介绍使用readli
- 定义一个绘制甘特图的类# -*- coding: utf-8 -*-from datetime import datetimeimport
- 桑基图,它的核心是对不同点之间,通过线来连接。线的粗细代表流量的大小。很多工具都能实现桑基图,比如:Excel、tableau,我们今天要用
- 废话不多说,先给大家展示一下效果图,如果大家感觉不错,请参考实现代码。效果图如下所示:代码如下所示:<!DOCTYPE html PU
- 本文详细讲述了MYSQL日志的正确删除方法。分享给大家供大家参考,具体如下:1.查找:MySQL> show binary logs;
- 本来想着做一个将图片识别为文字的小功能,本想到Google上面第一页全是各种收费平台的广告。这些平台提供的基本都是让我们通过调用相关的三方接
- 今天填一个坑,俄罗斯方块!!俄罗斯方块的移动不难实现,但是旋转就不太容易实现,究其原因是因为Python中没有数组这种数据结构,所以不能用矩
- 简介使用的核心模块是python标准库中的zipfile模块。这个模块可以实现zip文件的各种功能,具体可以查看官方参考文档。这里的暴力破解
- 异常处理程序运行时,发生的不被期望的事件,它阻止了程序按照程序员的预期正常执行,这就是异常golang中提供了两种处理异常的方式一种是程序发
- Python中有很多运算符,今天我们就来讲讲is和==两种运算符在应用上的本质区别是什么。在讲is和==这两种运算符区别之前,首先要知道Py
- 微信好友全头像话不多说,直接上代码import itchatimport mathimport PIL.Image as Imageimpo
- 方法一: 1、在DOS窗口下输入net stop mysql5 或 net stop mysql 2、开一个DOS窗口,这个需要切换到mys
- 本文实例讲述了python使用正则表达式匹配字符串开头并打印的方法。分享给大家供大家参考,具体如下:import res="nam
- Python中有3种内建的数据结构:列表、元组和字典。参考简明Python教程1. 列表list是处理一组有序项目的数据结构,即你可以在一个
- 在SQL语句优化过程中,我们经常会用到hint,现总结一下在SQL优化过程中常见Oracle HINT的用法:1. /*+ALL_ROWS*
- 0x00 识别涉及技术验证码识别涉及很多方面的内容。入手难度大,但是入手后,可拓展性又非常广泛,可玩性极强,成就感也很足。验证码图像处理验证
- Python 在其定义中提供了执行就地操作的方法,即使用“ operator ”
- mybatis-plus使用时候的小问题记录。在使用mybatis-plus的时候需要把sql的语句打印出来,查看执行的成功与否,在以前的项
- 说明为水平排列的表单和内联表单设置可选的图标.示例<!DOCTYPE html><html lang="zh-C
- Mysql Explain 详解一.语法explain < table_name >例如: explain select * f