【问题标题】:Python forking inside multithreadingPython 在多线程中分叉
【发布时间】:2015-03-28 18:09:57
【问题描述】:

我想要一个服务器和一个检查网络中所有计算机的功能。我想在固定的时间段内定期调用计算机检查功能。所以我想使用“选择”来包含服务器和功能。是否允许将函数作为参数传递给 select 还是只允许将列表传递给 select?

你建议我怎么做才能每 5 秒左右调用一次函数?

【问题讨论】:

    标签: python multithreading select server


    【解决方案1】:

    尝试实现您自己的线程,每五秒调用一次传递的函数。

    from threading import *
    import time
    
    def my_function():
        print 'Running ...' # replace
    
    class EventSchedule(Thread):
        def __init__(self, function):
            self.running = False
            self.function = function
            super(EventSchedule, self).__init__()
    
        def start(self):
            self.running = True
            super(EventSchedule, self).start()
    
        def run(self):
            while self.running:
                self.function() # call function
                time.sleep(5) # wait 5 secs
    
        def stop(self):
            self.running = False
    
    thread = EventSchedule(my_function) # pass function
    thread.start() # start thread
    

    【讨论】:

    • 其实这段代码是错误的,因为我忘记覆盖start方法。它现在应该可以工作了。
    • 这里不用调用run吗??
    • 还是start()执行完后自动执行?
    【解决方案2】:

    只需使用threading.Timer

    import threading
    
    def check_func():
        # other stuff
        threading.Timer(5.0, check_func).start()  # run check_func after 5s
    
    check_func()
    

    这是在 python 中执行周期性工作的标准方法。

    【讨论】:

    • 不。那只是在 5 秒后调用它。它不会定期执行任何操作。
    猜你喜欢
    • 2023-03-19
    • 1970-01-01
    • 2011-09-28
    • 2021-05-31
    • 2010-11-30
    • 1970-01-01
    • 1970-01-01
    • 2013-04-27
    • 1970-01-01
    相关资源
    最近更新 更多