zoukankan      html  css  js  c++  java
  • python做中学(九)定时器函数的用法

        程序中,经常用到这种,就是需要固定时间执行的,或者需要每隔一段时间执行的。这里经常用的就是Timer定时器。Thread 类有一个 Timer子类,该子类可用于控制指定函数在特定时间内执行一次。

       可以用几个例子来说明Timer的用法,

       一 最简单的用法,N s后(2s)后执行:

     1 #python3 example
     2 from threading import Timer
     3 import time
     4 
     5 
     6 def hello_test():
     7     print("hello world")
     8 
     9 t = Timer(2.0,hello_test)
    10 t.start()

        运行结果:

    ➜  timer git:(master) ✗ py timer_test1.py
    hello world

        二  每隔一秒执行一次,执行十次:

     1 #python3 example
     2 from threading import Timer
     3 import time
     4 
     5 count = 0
     6 def print_timer():
     7     global t, count
     8     print("count:%d new time: %s" % (count,time.ctime()))
     9     count += 1
    10 
    11     if count < 10:
    12         t = Timer(1, print_timer)
    13         t.start()
    14 
    15 t = Timer(1.0, print_timer)
    16 t.start()

         运行结果:

     1 ➜  timer git:(master) ✗ py timer_test2.py
     2 count:0 new time: Tue Aug 20 14:20:13 2019
     3 count:1 new time: Tue Aug 20 14:20:14 2019
     4 count:2 new time: Tue Aug 20 14:20:15 2019
     5 count:3 new time: Tue Aug 20 14:20:16 2019
     6 count:4 new time: Tue Aug 20 14:20:17 2019
     7 count:5 new time: Tue Aug 20 14:20:18 2019
     8 count:6 new time: Tue Aug 20 14:20:19 2019
     9 count:7 new time: Tue Aug 20 14:20:20 2019
    10 count:8 new time: Tue Aug 20 14:20:21 2019
    11 count:9 new time: Tue Aug 20 14:20:22 2019

       
        三 带参数输入的timer,每隔一秒执行一次,执行十次:

        

     1 #python3 example
     2 from threading import Timer
     3 import time
     4 
     5 def print_val(cnt):
     6     print("cnt:%d new time: %s" % (cnt,time.ctime()))
     7     cnt += 1
     8 
     9     if cnt < 10:
    10         t = Timer(1, print_val,(cnt,))
    11         t.start()
    12     else:
    13         return
    14 
    15 t = Timer(2.0, print_val,(1,))
    16 t.start()

           运行结果:

        

     1 ➜  timer git:(master) ✗ py timer_test.py
     2 cnt:1 new time: Tue Aug 20 14:23:31 2019
     3 cnt:2 new time: Tue Aug 20 14:23:32 2019
     4 cnt:3 new time: Tue Aug 20 14:23:33 2019
     5 cnt:4 new time: Tue Aug 20 14:23:34 2019
     6 cnt:5 new time: Tue Aug 20 14:23:35 2019
     7 cnt:6 new time: Tue Aug 20 14:23:36 2019
     8 cnt:7 new time: Tue Aug 20 14:23:37 2019
     9 cnt:8 new time: Tue Aug 20 14:23:38 2019
    10 cnt:9 new time: Tue Aug 20 14:23:39 2019

       从上面的例子可以看出,timer的基本用法是比较简单的,这个是不是对你有用呢?

    参考文档:

    http://c.biancheng.net/view/2629.html

      

  • 相关阅读:
    PyPi 是什么
    Python 项目结构
    Python 四舍五入函数 round
    Discourse 备份时间的设置
    Discourse 如何限制存储到 S3 的备份文件数量
    PHP中关于 basename、dirname、pathinfo 详解
    PHP中的魔术方法和关键字
    PHP中的排序函数sort、asort、rsort、krsort、ksort区别分析
    mysql cursor游标的使用,实例
    mysql 存储过程
  • 原文地址:https://www.cnblogs.com/dylancao/p/11382676.html
Copyright © 2011-2022 走看看