简体   繁体   English

为什么我应该使用threading.Timer而不是Loop + Sleep?

[英]Why I should use threading.Timer instead of a Loop + Sleep?

I'm new to Python and it seems like I have to write a Script which is able to work parallel. 我是Python的新手,看来我必须编写一个能够并行工作的Script。 Well, I decided to try to build a multi-threading script which is actual working fine I guess. 好吧,我决定尝试构建一个多线程脚本,我认为它确实可以正常工作。 While doing research I found many examples but only a few worked for me. 在进行研究时,我发现了很多例子,但只有少数例子对我有用。 Finally I read this question (Stackoverflow questions/474528 - second Answer - fifths comment) : 最后,我读了这个问题(Stackoverflow Questions / 474528-第二个答案-第五个注释)

The documentation of the shed module also points to the threading.Timer class, which is better suited for multithreaded environments. 棚模块的文档还指向threading.Timer类,它更适合于多线程环境。

For me this sounds like threading.Timer is the better function to use for me in this case. 对我来说,这听起来像是线程。在这种情况下,Timer是更好的函数。 Then I was wondering why ... maybe before I'll go on, on the same link above, the first comment on the second answer, someone is asking 然后我想知道为什么...也许在我继续之前,在上面的同一链接上,对第二个答案的第一个评论,有人问

The sched module is for scheduling functions to run after some time, how do you use it to repeat a function call every x seconds without using time.sleep()? sched模块用于安排函数在一段时间后运行,如何使用它在不使用time.sleep()的情况下每隔x秒重复一次函数调用?

Now I was thinking about, how can an function be better or not, if I have to Loop and Sleep anyway. 现在我正在考虑,如果无论如何我都要循环和睡眠,如何改善或不改善功能。 I mean the Timer's first parameter only says how long he should wait until start. 我的意思是,计时器的第一个参数仅表示他应该等待多长时间才能开始。 I tried a little workaround: 我尝试了一些解决方法:

#! C:\Python34\env python.exe
# -*- coding: utf-8 -*-

import threading
import time

class c_Thread ( threading.Thread ):
    sThreadName = ''
    iThreadInterval = 0

    def __init__ ( self, sThreadName, iThreadInterval ):
        threading.Thread.__init__ ( self )
        self.sThreadName = sThreadName
        self.iThreadInterval = iThreadInterval
        print ( )

    def run ( self ):
        print ( "Starting " + self.sThreadName )
        print_time ( self.sThreadName, self.iThreadInterval )
        print ( "Exiting " + self.sThreadName )
        print ( )

def print_time( sThreadName, iThreadInterval):
    while True:
        time.sleep(iThreadInterval)
        print ( sThreadName + ": " + time.ctime ( time.time ( ) ) )

Thread1 = c_Thread ( "ThreadOne", 2 )
Thread2 = c_Thread ( "ThreadTwo", 5 )

Thread1.start ( )
Thread2.start ( )

print ("Exiting Main Thread")

This Script is working fine. 该脚本运行良好。 Now I thought about okay, but why I should use a sleep tho, if the Timer function got the same functionality anyway. 现在我想到了可以,但是如果Timer函数无论如何都具有相同的功能,为什么还要使用sleep。 So I tried: 所以我尝试了:

#! C:\Python34\env python.exe
# -*- coding: utf-8 -*-

import threading
import time

class c_Thread ( threading.Thread ):
    sThreadName = ''
    iThreadInterval = 0

    def __init__ ( self, sThreadName, iThreadInterval ):
        threading.Thread.__init__ ( self )
        self.sThreadName = sThreadName
        self.iThreadInterval = iThreadInterval

    def run ( self ):
        print ( "Register Timer-Thread: " + self.sThreadName )
        while True:
            hTimer = threading.Timer ( self.iThreadInterval, print_time, ( self.sThreadName ) )
            hTimer . start ( )

def print_time( sThreadName ):
    print ( sThreadName + ": " + time.ctime ( time.time ( ) ) )

Thread1 = c_Thread ( "One", 2 )
Thread2 = c_Thread ( "Two", 5 )

Thread1 . start ( )
Thread2 . start ( )

But actual I don't get this running correct ... I'm getting this error: 但是实际上我没有正确运行此命令...我收到此错误:

TypeError: print_time() takes 1 positional arguments but 3 were given TypeError:print_time()接受1个位置参数,但给出了3个

I did some research and I found out that the 'self' is the first object so I added the self on the parameters on print_time. 我做了一些研究,发现“自我”是第一个对象,因此我在print_time的参数上添加了自我。

def print_time( self, sThreadName ):

At the beginning I only had the 'sThreadName' as parameter. 刚开始,我只有'sThreadName'作为参数。 So the second one is 'sThreadname', but where does a third one comes from? 所以第二个是“ sThreadname”,但是第三个是哪里来的呢?

I did prints for debugging, added a third parameter but don't use it. 我做了打印调试用,添加了第三个参数,但是不使用它。

def print_time( self, sThreadName, idk ):
    #print ( "self: " + self )
    #print ( "sThreadName: " + sThreadName )
    #print ( "idk: " + idk)
    #print ( )
    print ( sThreadName + ": " + time.ctime ( time.time ( ) ) )

but then the 'sThreadname' is not correct, it's always like single-letters (eg 'n') ... maybe at this point can someone help me out here too? 但是然后'sThreadname'是不正确的,它总是像单字母(例如'n')...也许在这一点上有人也可以帮我吗?

Besides the fact that the 'sThreadName' is wrong, in case that I'm using 3 parameters on my function and ignore the third one (no usage), my script is not doing what I'm expecting. 除了“ sThreadName”是错误的事实之外,如果我在函数上使用了3个参数而忽略了第三个参数(无用法),我的脚本也没有达到我的期望。 Im expecting the exactly same behaviour like in my first script posted above. 我期望与上面发布的第一个脚本完全相同的行为。 Why this is not the case. 为什么不是这种情况。 I really wanna unterstand this. 我真的很想理解这一点。

So far, thanks in advice for everyone who will try to help me out. 到目前为止,感谢所有将帮助我的人的建议。 Regards, Mike. 问候,迈克。

Environment: Windows 7 Professional 64-Bit Python 3.4 Code-Editor: Notepad++ Running on CMD by 'python -tt script.py' 环境:Windows 7 Professional 64位Python 3.4代码编辑器:Notepad ++通过'python -tt script.py'在CMD上运行

Change this: 更改此:

def run ( self ):
    print ( "Register Timer-Thread: " + self.sThreadName )
    while True:
        hTimer = threading.Timer ( self.iThreadInterval, print_time, ( self.sThreadName ) )
        hTimer . start ( )

too: 太:

def run ( self ):
    print ( "Register Timer-Thread: " + self.sThreadName )
    while True:
        hTimer = threading.Timer ( self.iThreadInterval, print_time( self.sThreadName ) )
        hTimer . start ( )

so just: "print_time, ( self.sThreadName )" should be without the comma "print_time( self.sThreadName )" 就是这样:“ print_time,(self.sThreadName)”应该没有逗号“ print_time(self.sThreadName)”

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

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