[d]python定时器

wenskys 2012-09-04 05:23:03
各位兄弟大家好,我想用python来实现类似flex的setTimeout的方法,网上查了很多,都没有符合要求的,我要的是隔一段时间就执行一个操作,不知道大家有没有好的建议??????
--------------------------
Double行动:
原帖分数:20
...全文
766 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
iazxq3 2013-02-06
  • 打赏
  • 举报
回复
这有一个用线程实现的简单的定时器封装,不知道能不能帮到你 http://www.sharejs.com/codes/python/6420
bugs2k 2013-02-04
  • 打赏
  • 举报
回复
简单封装了一下
from threading import Timer

class MyTimer:
	
	def __init__(self):
		self._timer= None
		self._tm = None
		self._fn = None
	
	def _do_func(self):
		if self._fn:
			self._fn()
			self._do_start()

	def _do_start(self):
		self._timer = Timer(self._tm, self._do_func)
		self._timer.start()

	def start(self, tm, fn):
		self._fn = fn
		self._tm = tm
		self._do_start()

	def stop(self):
		try:
			self._timer.cancel()
		except:
			pass
			
def hello():
	from datetime import datetime
	print("hello world!", datetime.now())


if __name__ == '__main__':

	mt = MyTimer()
	mt.start(2, hello)
	for i in range(10):
		import time
		time.sleep(1)
	mt.stop()
A6252923 2013-02-03
  • 打赏
  • 举报
回复
不是很准,但也差不多了。可以用一下。不过,也只能用在反复循环的地方。
A6252923 2013-02-03
  • 打赏
  • 举报
回复
import time nextTime = time.time()+1 def getTime(k): nextTime = time.time()+1 while True: #print nextTime nowTime = time.time() if nowTime >= nextTime: print k nextTime = time.time()+1 if __name__ == "__main__": getTime(2)
手无护鸡之力 2012-09-20
  • 打赏
  • 举报
回复
我就是这么做的……
我想知道,是否类似功能模块也是这样实现的?像Windows的计划任务。还是有更有效率和科学的方法?

[Quote=引用 5 楼 的回复:]
很土的一个方法:自己开一个线程不停判断时间到即执行……
[/Quote]
angel_su 2012-09-19
  • 打赏
  • 举报
回复
试试sched模块...
  • 打赏
  • 举报
回复
很土的一个方法:自己开一个线程不停判断时间到即执行……
wenskys 2012-09-19
  • 打赏
  • 举报
回复
楼上的我试过了,我之前就是这样弄得,但是一次就可以,弄多一次就不行了
javacode007 2012-09-04
  • 打赏
  • 举报
回复
如果使用比较简单的话,无需第三方库吧,自己写一个定时器(采用多线程的方式)就OK了。或者直接调用 python 的 thread 模块的 Timer 类。说明如下:

class threading.Timer(interval, function, args=[], kwargs={})
Create a timer that will run function with arguments args and keyword arguments kwargs, after interval seconds have passed.

cancel()
Stop the timer, and cancel the execution of the timer’s action. This will only work if the timer is still in its waiting stage.

构造一个定时器,若在指定的时间未到之前,还可通过 cancel 取消。
Gloveing 2012-09-04
  • 打赏
  • 举报
回复
使用PyQt的QTimer
Gloveing 2012-09-04
  • 打赏
  • 举报
回复
使用PyQt的QTimer

37,742

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • WuKongSecurity@BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧