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

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

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

  1. print("threading active = {} \n \n".format(threading.enumerate()))
  2. #打印
  3. threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-1, started 123145498161152)>]
  4. threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-1, started 123145498161152)>]
  5. threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-1, started 123145498161152)>]
  6. threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-2, started 123145503416320)>]
  7. threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-2, started 123145503416320)>]
  8. threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-3, started 123145498161152)>]
  9. threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-3, started 123145498161152)>]

阅读源码和文档

  1. class Timer(Thread):
  2. """Call a function after a specified number of seconds:
  3. t = Timer(30.0, f, args=None, kwargs=None)
  4. t.start()
  5. t.cancel() # stop the timer's action if it's still waiting
  6. """
  7. def __init__(self, interval, function, args=None, kwargs=None):
  8. Thread.__init__(self)
  9. self.interval = interval
  10. self.function = function
  11. self.args = args if args is not None else []
  12. self.kwargs = kwargs if kwargs is not None else {}
  13. self.finished = Event()
  14. def cancel(self):
  15. """Stop the timer if it hasn't finished yet."""
  16. self.finished.set()
  17. def run(self):
  18. self.finished.wait(self.interval)
  19. if not self.finished.is_set():
  20. self.function(*self.args, **self.kwargs)
  21. self.finished.set()
  22. # Special thread class to represent the main thread
  23. # This is garbage collected through an exit handler

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


  1. def startTimer():
  2. global timer
  3. if timer != None:
  4. timer.finished.wait(timerFlag)
  5. timer.function()
  6. else:
  7. timer = threading.Timer(timerFlag, upload_position)
  8. timer.start()

打印结果:


  1. threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-1, started 123145516048384)>]
  2. threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-1, started 123145516048384)>]
  3. threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-1, started 123145516048384)>]
  4. threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-1, started 123145516048384)>]
  5. threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-1, started 123145516048384)>]
  6. 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文件下载(解决文件下载后多几个字节的问题) 与封装成类的例子

    php文件下载比较常见,网上的资料比较多,在此不再强调怎么去实现(因为也是网上看的).下面主要说明的是下载代码的注意点. php下载文件主要是把文件以字节流直接输出,也就是echo fread($fi ...

  2. mysql互为主从

    摘自:http://flash520.blog.163.com/blog/static/3441447520101029114016823/ A B 为两台MySQL服务器,均开启二进制日志,数据库版 ...

  3. Unity的JIT和AOT实现

    https://myhloli.com/about-il2cpp.html JIT方式: Unity的跨平台技术是通过一个Mono虚拟机实现的.而这个虚拟机更新太慢,不能很好地适应众多的平台. And ...

  4. NLP-Progress记录NLP最新数据集、论文和代码: 助你紧跟NLP前沿

    Github https://github.com/sebastianruder/NLP-progress 官方网址 https://nlpprogress.com/ NLP-Progress 同时涵 ...

  5. Spring Boot: Cannot determine embedded database driver class for database type NONE

    配置启动项时提示如下: 原因是:springboot启动时会自动注入数据源和配置jpa 解决: 1 在@SpringBootApplication中排除其注入 @SpringBootApplicati ...

  6. 配置Ubuntu虚拟环境

    1.ubuntu默认root用户没有激活,激活root用户,就要为root用户创建密码 $sudo passwd root   2.修改主机名 $vi /etc/hostname   3.安装ssh服 ...

  7. sqlalchemy--表关系

    通过表关系查数据能更简洁的查询到需要的内容 user, user1, article, user_article(为中间表user_article关联article和user)四个表 from dat ...

  8. windows,linux,esxi系统判断当前主机是物理机还是虚拟机?查询主机序列号命令

    参考网站:https://blog.csdn.net/yangzhenping/article/details/49996765 查序列号: http://www.bubuko.com/infodet ...

  9. 21. oracle游标循环例子

    事例1: create or replace procedure sp_addProjectQj( ret out number, flowid in number --流程Id) ascursor ...

  10. XMind8 安装

    参考:https://blog.csdn.net/qq_35911589/article/details/81901868 https://blog.csdn.net/Zjhao666/article ...