python实现循环定时器的方法介绍(附代码)


当前第2页 返回上一页

_Timer 是一个 Thread 子类,我们先看看 Thread 类的 run 用法。

1

2

3

4

5

6

7

8

9

10

from threading import Thread

def hello():

     print "hello, world"

# 继承 Thread

class MyThread(Thread):

    # 把要执行的代码写到run函数里面 线程在创建后会直接运行run函数

    def run(self):

        hello()

t = MyThread()

t.start()

Thread 对象的完整定义:

1

class threading.Thread(group=None, target=None, name=None, args=(), kwargs={})

其中 run 方法代码:

1

2

3

4

5

6

7

8

9

class Thread(_Verbose):

    def run(self):

        try:

            if self.__target:

                self.__target(*self.__args, **self.__kwargs)

        finally:

            # Avoid a refcycle if the thread is running a function with

            # an argument that has a member that points to the thread.

            del self.__target, self.__args, self.__kwargs

标准的 run 方法用于执行用户传入构造函数的 target 方法。 子类可以重写 run 方法,把要执行的代码写到 run 里面,线程在创建后,用户调用 start() 方法会运行 run() 方法。

所以 RepeatingTimer 重写 _Timer 的 run() 方法,可以改变线程的执行体,当我们调用 RepeatingTimer 的 start() 方法时会执行我们重写的 run() 方法。

再看看 RepeatingTimer 类中的 while not self.finished.is_set() 语句,self.finished.is_set() 直到 True 才会退出循环,定时器才结束。finished 是 threading.Event 对象。一个 Event 对象管理着一个 flag 标志,它能被 set() 方法设置为 True,也能被 clear() 方法设置为 False,调用 wait([timeout]) 线程会一直 sleep 到 flag 为 True 或超时时间到达。

我们知道定时器有一个 cancel() 方法可以提前取消操作。它其实是调用 Event.clear() 方法提前让 wait 方法结束等待,并且判断在 flag 为 true 的情况下不执行定时器操作。具体的代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

class _Timer(Thread):

    """Call a function after a specified number of seconds:

            t = Timer(30.0, f, args=[], kwargs={})

            t.start()

            t.cancel() # stop the timer's action if it's still waiting

    """

 

    def __init__(self, interval, function, args=[], kwargs={}):

        Thread.__init__(self)

        self.interval = interval

        self.function = function

        self.args = args

        self.kwargs = kwargs

        self.finished = Event()

 

    def cancel(self):

        """Stop the timer if it hasn't finished yet"""

        self.finished.set()

 

    def run(self):

        self.finished.wait(self.interval)

        if not self.finished.is_set():

            self.function(*self.args, **self.kwargs)

        self.finished.set()

所以 RepeatingTimer 的 run 方法会一直执行 while 循环体,在循环体了会执行用户传入的 function 对象,并等待指定的时间。当用户想退出定时器时,只需要调用 cancel 方法,将 flag 置为 True 便不会继续执行循环体了。这样便完成了一个还不错的循环定时器。

以上就是python实现循环定时器的方法介绍(附代码)的详细内容,更多文章请关注木庄网络博客!!

返回前面的内容

相关阅读 >>

关于pyzmq介绍

怎么用Python来读取和处理文件后缀?

str Python是什么意思

使用Python时多少有人走过的坑!避险!

Python编写图形界面如何利用aardio实现

Python中一些常见的错误

Python中格式化输出的两种方法介绍

Python如何停止运行

Python数据分析方向的第三方库是什么

Python有哪些需要学习的知识?

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...