【问题标题】:python schedule library to stop previously running thread when new scheduled thread startspython调度库在新的调度线程启动时停止先前运行的线程
【发布时间】:2020-10-17 21:42:20
【问题描述】:

我每 10 分钟运行一次相同的线程。但是当新线程启动时,我想退出前一个线程,这样它就不会继续增加空间。我怎样才能做到这一点。用于线程调度。我正在使用 python 调度库。

这就是我现在的日程安排

schedule.every(10).minutes.do(sts,threadFunc)

【问题讨论】:

    标签: python multithreading scheduling


    【解决方案1】:

    这个问题有两个方面:

    • 确定当前正在运行的作业,这相当容易。
    • 在 python 中杀死一个正在运行的线程。对此没有很好的解决方案,以下代码实现了“停止标志”方法。

    我正在通过使用全局变量来解决第一个挑战。这个名为running_thread 的变量保存了当前正在运行的线程,以便新作业可以在需要时终止它。

    第二个挑战要求正在运行的线程不断检查某个标志(“停止标志”)的状态。如果在该线程上设置了停止标志,它会立即存在。

    这是一个演示这两个想法的代码框架。作业需要随机的时间,我已安排它们每 1 秒启动一次。

    import threading
    import time
    import schedule
    import random 
    
    running_thread = None
    
    class StoppableThread(threading.Thread):
        """Thread class with a stop() method. The thread itself has to check
        regularly for the stopped() condition."""
    
        def __init__(self,  *args, **kwargs):
            super(StoppableThread, self).__init__(*args, **kwargs)
            self._stop_event = threading.Event()
    
        def stop(self):
            self._stop_event.set()
    
        def stopped(self):
            return self._stop_event.is_set()
    
    def job():
        current_thread = threading.currentThread()
        sleep_time = random.random() * 5
    
        
        print(f"Starting job, about to sleep {sleep_time} seconds, thread id is {current_thread.ident}")
        counter = 0 
        while counter < sleep_time:
            time.sleep(0.1)
            counter += 0.1
            if current_thread.stopped():
                print ("Stopping job")
                break
        print(f"job with thread id {current_thread.ident} done")
    
    def threadFunc(): 
        global running_thread
        if running_thread: 
            print("Trying to stop thread")
            running_thread.stop()
        print("Strting thread")
        running_thread = StoppableThread(target = job)
        running_thread.start()
    
    schedule.every(1).seconds.do(threadFunc)
    
    while True:
        schedule.run_pending()
        time.sleep(.5)
    

    【讨论】:

      猜你喜欢
      • 2013-10-06
      • 2012-07-10
      • 2019-02-02
      • 1970-01-01
      • 2020-04-11
      • 2020-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多