创建自己的定时执行线程

import threading
import time


class MyScheduledTask(threading.Thread):
def __init__(self, interval, func, args=[], kwargs={}):
super().__init__()
self.interval = interval
self.function = func
self.args = args
self.kwargs = kwargs
self.finished = threading.Event()

def run(self):
while not self.finished.isSet():
self.function(*self.args, **self.kwargs)
self.finished.wait(self.interval)
print(f"线程{threading.current_thread().name}停止")

def stop(self):
self.finished.set()


def check_heart_beat(ip, port, width, width_offset):
print(ip, port, width, width_offset)
print(f"检查心跳")


if __name__ == "__main__":
task_thread = MyScheduledTask(2, check_heart_beat, args=["192.168.247.234", "502", 50, 2])
task_thread.start()
print("子线程开始了,10秒后我让他结束")
time.sleep(10)
task_thread.stop()
上一篇:python之第一个例子hello world


下一篇:测试理论基础知识学习总结