简体   繁体   English

python 调度库在新的调度线程启动时停止先前运行的线程

[英]python schedule library to stop previously running thread when new scheduled thread starts

I have a same thread running every 10 min.我每 10 分钟运行一次相同的线程。 but when the new thread starts i want to quit the previous thread so it doesn't keep adding up the space.但是当新线程启动时,我想退出前一个线程,这样它就不会继续增加空间。 how can i achieve that.我怎样才能做到这一点。 for scheduling of thread.I'm using python schedule library.用于线程调度。我正在使用 python 调度库。

this is how I'm scheduling right now这就是我现在安排的方式

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

There are two aspects to this question:这个问题有两个方面:

  • identify the currently running job, which is fairly easy.识别当前正在运行的作业,这相当容易。
  • Kill a running thread in python.杀死 python 中正在运行的线程。 There's no great solution for this, and the following code implements the 'stop flag' approach.对此没有很好的解决方案,以下代码实现了“停止标志”方法。

I'm solving the first challenge by using a global variable.我正在通过使用全局变量来解决第一个挑战。 This variable, named running_thread , holds the currently running thread so that a new job can kill it if needed.这个名为running_thread的变量保存当前正在运行的线程,以便新作业可以在需要时终止它。

The second challenge requires the running thread to constantly check the status of some flag ('the stop flag').第二个挑战要求正在运行的线程不断检查某个标志(“停止标志”)的状态。 If the stop flag is set on that thread, it immediately exists.如果在该线程上设置了停止标志,它会立即存在。

Here's a code skeleton that demonstrates both these ideas.这是一个演示这两个想法的代码框架。 Jobs take a random amount of time, and I've scheduled them to start every 1 second.作业需要随机的时间,我已安排它们每 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)

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

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