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

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. php如何判断IP为有效IP地址

    不需要正则表达式来判断,因为在php5.2.0之后,有专门的函数来做这个判断了. 判断是否是合法IP if(filter_var($ip, FILTER_VALIDATE_IP)) { // it's ...

  2. 特征选择:方差选择法、卡方检验、互信息法、递归特征消除、L1范数、树模型

    转载:https://www.cnblogs.com/jasonfreak/p/5448385.html 特征选择主要从两个方面入手: 特征是否发散:特征发散说明特征的方差大,能够根据取值的差异化度量 ...

  3. 【C++11新特性】 nullptr关键字

    原文链接:http://blog.csdn.net/xiejingfa/article/details/50478512 熟悉C++的童鞋都知道,为了避免“野指针”(即指针在首次使用之前没有进行初始化 ...

  4. 蓝瓶的钙,好喝的钙——windows,我要蓝屏的

    原文地址:http://80x86.io/post/windows-blue-screen-0x00000050-page_fault_in_nonpaged_area 这里只截取一部分. windo ...

  5. 处理存在UNASSIGNED的主分片导致Elasticsearch集群状态为Red的问题

    我们默认是开启了自动分配的,但仍然会因为服务器软硬件的原因导致分配分配失败,从而出现UNASSIGNED的分片,如果存在该状态的主分片则会导致集群为Red状态.此时我们可以通过reroute API进 ...

  6. HTML5进阶

    内容: 1.geolocation元素 2.video元素和audio元素 3.localStorage 4.WebWorker 5.WebSQL.IndexedDB 6.文件操作.文件拖拽新概念 7 ...

  7. Python环境搭建之OpenCV

    一.openCV介绍 Open Source Computer Vision Library.OpenCV于1999年由Intel建立,如今由Willow Garage提供支持.OpenCV是一个基于 ...

  8. IP分组交付和转发

    1:交付 网络层监视底层物理网络对分组的处理过程叫做交付,分为直接交付和间接交付 1.1:直接交付 直接交付时,分组的终点是一台与交付着连接在同一个网络上的主机,发生在俩种情况下,分组的源点和终点都在 ...

  9. OpenACC 简单的原子操作

    ▶ OpenACC 的原子操作,用到了 C++ 的一个高精度计时器 ● 代码,直接的原子操作 #include <iostream> #include <cstdlib> #i ...

  10. windows配置ftp服务器

    一.搭建FTP 二.解决FTP因windows防火墙拦截的方法 三.配置FTP用户 ========================================================== ...