简体   繁体   English

Python-如何正确终止threading.Timer类?

[英]Python - how to terminate a threading.Timer class correctly?

I'm currently experimentating around with threading.Timer, and somehow I'm not doing very well.. My goal is to run hundreds of functions, repeating all the time. 我目前正在试验threading.Timer,但我做得不太好。我的目标是运行数百个函数,并始终重复执行。 The problem is, that the usage of my RAM is growing and growing and growing, until the process stops. 问题是,我的RAM的使用在不断增长,直到该过程停止为止。

This is how my code looks like: 这是我的代码的样子:

from threading import Timer

class Foo:
    def __init__(self, number):
        self.number = number
        self.timer = Timer(1, self.print_number)
        self.timer.start()

    def print_number(self):
        print "Number: %s"%self.number
        self.repeat()

    def repeat(self):
        self.timer.cancel()
        #self.timer.join()
        #time.sleep(1)
        self.timer = Timer(3, self.print_number)
        self.timer.start()

for x in range(1, 300):
    Foo(x)

So, I've read that I can terminate a thread using .join() method after .cancel(). 因此,我读到可以在.cancel()之后使用.join()方法终止线程。 But when I do this I'm getting a RuntimeError: (cannot join current thread) . 但是,当我这样做时,我得到一个RuntimeError: (cannot join current thread) On a similar topic I've read that I can use time.sleep after .cancel() to terminate a thread, but that does nothing to the thread for me. 在类似的主题上,我读到可以在.cancel()之后使用time.sleep来终止线程,但这对线程没有任何帮助。

My questions: How can I properly terminate the threads in this code example and how can I stop the script from using more and more RAM, or am I doing something terribly wrong? 我的问题:如何在此代码示例中正确终止线程,如何停止脚本使用越来越多的RAM,或者我做错了什么?

Sorry if I'm re-asking a question that has been asked already many times, but I'm searching and trying for hours and couldn't find a solution yet. 抱歉,如果我要问一个已经被问过很多次的问题,但是我正在搜索并尝试了几个小时,还找不到解决方案。

Thanks in advance. 提前致谢。

Something like this? 像这样吗 Just have a break condition in the loop. 只是在循环中有一个休息条件。 The join at the end just makes sure all threads finish before moving forward. 最后的联接只是确保所有线程在继续前进之前完成。 I use this often with a Queue (you can find samples, Queue Work Task pattern or some similar search). 我经常将其与队列一起使用(您可以找到样本,队列工作任务模式或一些类似的搜索)。

Alternatively, I use apscheduler when I just need things to run on a timer or some cron-like functionality. 另外,当我只需要在计时器上运行某些东西或类似cron的功能时,我会使用apscheduler。

import threading
import time

WORKERS = 300

class Worker(threading.Thread):

    def __init__(self, number):
        self.number = number
        threading.Thread.__init__(self)

    def run(self):
        while 1:
            if self.number > 300:
                break

            print "Number: %s"%self.number
            self.number += 1
            time.sleep(3)

workers = []
for i in range(WORKERS):
    w = Worker(100)
    workers.append(w)
    w.start()

for w in workers: 
    w.join()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM