Chinaunix

标题: python 定时器 [打印本页]

作者: markangelma    时间: 2009-11-21 23:57
标题: python 定时器
初始化一个定时器,希望在不用的时候可以删除,但是总是不行,代码如下,哪里不对呢~~~
from threading import Timer
from time import ctime, sleep

class foo:
    def __init__(self):
        pass
   
    def disconnect(self):
        self.timer.cancel()
        print('dead...')

    def keepAlive(self):
        print('aliving...')
        self.timer = Timer(1, self.keepAlive)
        self.timer.start()

f = foo()
f.keepAlive()
for i in range(3):
    print(i)
    sleep(1)
f.disconnect()
作者: miocn    时间: 2009-11-22 11:55
标题: 回复 #1 markangelma 的帖子
同求这个问题,我之前曾在邮件列表中请教,limodou老大回复说  self.timer.cancel()并不能真正关闭该进程。
后来我一直没法解决 。。。  
郁闷中。。。
作者: markangelma    时间: 2009-11-22 12:56
感觉是...,可是我在执行定时器的过程中sleep一段时间后,在调用Timer.cancel()貌似可以,不知道又是怎么回事。如果用执行代码替换sleep语句,比如ftp长连接过程中是否可以。
from threading import Timer
from time import ctime, sleep

class foo:
    def __init__(self):
        pass
   
    def disconnect(self):
        self.timer.cancel()
        print('dead...')

    def keepAlive(self):
        print(ctime(), 'aliving...')
        self.timer = Timer(1, self.keepAlive)
        self.timer.start()

f = foo()
f.keepAlive()
sleep(9)
f.disconnect()

执行结果:
>>>
('Sun Nov 22 12:51:50 2009', 'aliving...')
('Sun Nov 22 12:51:51 2009', 'aliving...')
('Sun Nov 22 12:51:52 2009', 'aliving...')
('Sun Nov 22 12:51:53 2009', 'aliving...')
('Sun Nov 22 12:51:55 2009', 'aliving...')
('Sun Nov 22 12:51:56 2009', 'aliving...')
('Sun Nov 22 12:51:57 2009', 'aliving...')
('Sun Nov 22 12:51:58 2009', 'aliving...')
('Sun Nov 22 12:51:59 2009', 'aliving...')
dead...
>>>
作者: nietsche    时间: 2009-11-22 14:16
不要把self.timer定义在keepAlive函数中。

from python help:

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.
作者: markangelma    时间: 2009-11-22 14:31
标题: 回复 #4 nietsche 的帖子
不在函数体内定义的话,有什么办法能够得到返回值,用来调用cancel呢?
作者: asxxi1    时间: 2011-09-06 16:23
from threading import Timer
from time import ctime, sleep

def timer_cb():
    global timer
    print(ctime(), 'aliving...')
    timer = Timer(0.5, timer_cb)  
    timer.start()
   
timer = Timer(0.5, timer_cb)  
timer.start()
sleep(3)
timer.cancel()
print('dead...')

我不用对象,就可以停止了,那个timer是全局变量,可能跟线程有关吧,全局变量能在线程中共享,
所以估计不能用self的。
作者: 106033177    时间: 2011-09-07 10:44
回复 1# markangelma
用不着cancle 只要停止生成新线程就行了,比如简单加个标志。
  1. class foo:
  2.     def __init__(self):
  3.         self.flag=True   
  4.     def disconnect(self):
  5.         self.flag=False
  6.         print('dead...')
  7.     def keepAlive(self):
  8.         if not self.flag:
  9.             return            
  10.         print('aliving...')
  11.         self.timer = Timer(1, self.keepAlive)
  12.         self.timer.start()
  13. f = foo()
  14. f.keepAlive()
  15. for i in range(3):
  16.     print(i)
  17.     sleep(1)
  18. f.disconnect()
复制代码





欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2