项目中需要使用定时器,每次都使用构造器函数调用:

timer = threading.Timer(timerFlag, upload_position)
timer.start()

打印线程后发现,每次都会创建一个新的子线程,虽然活跃的线程只有一个,但是也是种资源浪费:

print("threading active = {} \n   \n".format(threading.enumerate()))

#打印
threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-1, started 123145498161152)>]
threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-1, started 123145498161152)>]
threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-1, started 123145498161152)>] threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-2, started 123145503416320)>]
threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-2, started 123145503416320)>] threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-3, started 123145498161152)>]
threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-3, started 123145498161152)>]

阅读源码和文档

class Timer(Thread):
"""Call a function after a specified number of seconds: t = Timer(30.0, f, args=None, kwargs=None)
t.start()
t.cancel() # stop the timer's action if it's still waiting """ def __init__(self, interval, function, args=None, kwargs=None):
Thread.__init__(self)
self.interval = interval
self.function = function
self.args = args if args is not None else []
self.kwargs = kwargs if kwargs is not None else {}
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() # Special thread class to represent the main thread
# This is garbage collected through an exit handler

发现,其实Timer是threading的子类,用wait实现了定时效果,绑定了入参function,于是修改代码如下


def startTimer():
global timer
if timer != None:
timer.finished.wait(timerFlag)
timer.function()
else:
timer = threading.Timer(timerFlag, upload_position)
timer.start()

打印结果:


threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-1, started 123145516048384)>] threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-1, started 123145516048384)>] threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-1, started 123145516048384)>] threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-1, started 123145516048384)>] threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-1, started 123145516048384)>] threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-1, started 123145516048384)>]

始终只有一个线程且重复调用函数方法~End~

   

   

   

友情链接:

个人网站       技术博客        简书主页

Python threading 单线程 timer重复调用函数的更多相关文章

  1. Python:学会创建并调用函数

    这是关于Python的第4篇文章,主要介绍下如何创建并调用函数. print():是打印放入对象的函数 len():是返回对象长度的函数 input():是让用户输入对象的函数 ... 简单来说,函数 ...

  2. 无限调用函数add(1)(2)(3)......

    无限调用函数,并且累计结果 其实这也算一道面试题吧,笔者曾经被提问过,可惜当时没能答上来...

  3. Python 学习 第七篇:函数1(定义、调用和变量的作用域)

    函数是把一些语句集合在一起的程序结构,用于把复杂的流程细分成不同的组件,能够减少代码的冗余.代码的复用和修改代码的代价. 函数可以0个.1个或多个参数,向函数传递参数,可以控制函数的流程.函数还可以返 ...

  4. Python之调用函数

    Python之调用函数 Python内置了很多有用的函数,我们可以直接调用. 要调用一个函数,需要知道函数的名称和参数,比如求绝对值的函数 abs,它接收一个参数. 可以直接从Python的官方网站查 ...

  5. python 调用函数

    Python内置了很多有用的函数,我们可以直接调用. 要调用一个函数,需要知道函数的名称和参数,比如求绝对值的函数abs,只有一个参数.可以直接从Python的官方网站查看文档: http://doc ...

  6. python入门(13)获取函数帮助和调用函数

    Python内置了很多有用的函数,我们可以直接调用. 要调用一个函数,需要知道函数的名称和参数,比如求绝对值的函数abs,只有一个参数.可以直接从Python的官方网站查看文档: http://doc ...

  7. python调用函数超时设置

    1.Windows中sign报错,Linux能很好的使用: https://pypi.python.org/pypi/timeout-decorator 2.Windows可以使用,Linux报错不能 ...

  8. 『Python』为什么调用函数会令引用计数+2

    一.问题描述 Python中的垃圾回收是以引用计数为主,分代收集为辅,引用计数的缺陷是循环引用的问题.在Python中,如果一个对象的引用数为0,Python虚拟机就会回收这个对象的内存. sys.g ...

  9. python函数(一)调用函数

    在python中内置了很多函数或者类,比如:int,str,list,tuple,等.当然也可以自建函数,这个放在后文讨论.原理如下: 其实python中的类和方法非常非常多,这里只是以点带面,提供一 ...

随机推荐

  1. MYSQL中只知表名查询属于哪个SCHEMA

    只知道表名XXX查该表属于哪个schema.以及该表有哪些列等信息 SELECT * from information_schema.columns WHERE table_name = 'xxx'; ...

  2. CART、GradientBoost

    转载:https://blog.csdn.net/niuniuyuh/article/details/76922210 论文:http://pdfs.semanticscholar.org/0d97/ ...

  3. unity3d之Editor的Assembly-CSharp.dll文件路径

    在Editor中与自己project中使用的Mono与Managed文件夹路径区别: Editor中:在unity安装路径[AppDir]下: 自己project中:在project的路径下,由bui ...

  4. 【Codeforces】CF 911 D. Inversion Counting(逆序对+思维)

    题目 传送门:QWQ 分析 思维要求比较高. 首先我们要把原图的逆序对q算出来. 这个树状数组或归并排序都ok(树状数组不用离散化好评) 那么翻转$[l,r]$中的数怎么做呢? 暴力过不了,我试过了. ...

  5. js && Jquery 的回车事件

    有时候我们需要捕获页面上的回车事件,以达到一些特殊效果,例如在登录页面用户输入完登录名和密码后习惯直接敲回车,这时需要捕获回车事件,在回车事件中激活form元素 1.纯Java Script版 首先要 ...

  6. C# AtomicBoolean

    using System; using System.Threading; /// <summary> /// Provides lock-free atomic read/write u ...

  7. python读取文件中的字典

    import ast def file_read():    with open('D:\\pytharm\\jichuyufa\\day2\\pro_cty_con.txt', 'r', encod ...

  8. 学习MongoDB 四: MongoDB查询(一)

    一.简介 MongoDB提供了db.collection.find() 方法可以实现根据条件查询和指定使用投影运算符返回的字段省略此参数返回匹配文档中的所有字段. 二.db.collection.fi ...

  9. django中使用Form组件

    内容: 1.Form组件介绍 2.Form组件常用字段 3.Form组件校验功能 4.Form组件内置正则校验 参考:https://www.cnblogs.com/liwenzhou/p/87478 ...

  10. html-文本属性

    1.文本标记线 text-decoration: 下划线-underline 删除线-line-through 上划线-overline 2.文本大小写 text-transform 默认值none ...