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

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. LVM逻辑卷创建管理

    首先添加三块硬盘 结构关系图 相关命令 查看磁盘 #fdisk -l 分区 #fdisk /dev/sda/ #n新建 ProMary主分区 extended扩展分区 #p查看 #q不保存退出 #w保 ...

  2. python之路_函数实例及装饰器介绍

    一.习题讲解 1.写函数,返回一个扑克牌列表,里面有52项,每一项是一个元组.例如:[(‘红心’,2), (‘草花’,2), …(‘黑桃,‘A’)] def cards(): num=[] for v ...

  3. 使用Python调用动态库

    我个人在日常使用电脑时,经常需要使用Google,于是就要切换代理,基本上是一会儿切换为代理,一会儿切换成直连,老是打开internet 选项去设置,很不方便,于是我萌生了一个想法: 做一个开关,我想 ...

  4. HTML5 浏览器接收的常用 content-type

    <1> 常见的设置方法 response.setHeader("content-type", 'text/html'); <2> 浏览器接收的常用 cont ...

  5. NavitForMySql 破解工具使用

    Navicat 11.0注册机使用教程: 1.右键-管理员权限运行注册机2.选择对应的产品3.点击“补丁”按钮,选择文件4.点击“生成”按钮,生成序列号,并保存下授权文件5.复制序列号,打开软件,在弹 ...

  6. C# 通用方法

    一. /// <summary> /// 删除字符串中的中文 /// </summary> public static string Delete(string str) { ...

  7. Python之filter函数

    描述 filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表. 该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 Tru ...

  8. clamav杀毒软件的安装

    Linux Unix.Trojan.Elknot (Linux.BackDoor.Gates.5)木马清理 此恶意软件结合了传统后门程序和DDoS攻击木马的功能 前两天性能测试服务器被种马,cpu一直 ...

  9. 软件工程导论九月26号Homework

    习题3 (1)数据流图 (2)实体关系图ER 习题6

  10. Containerpilot 配置文件 之 Telemetry

    如果提供telemetry选项,ContainerPilot将公开可用于刮擦性能telemetry的Prometheus HTTP客户端界面. telemetry接口被公告为consul服务. tel ...