定时器和函数执行时间限制

2022-11-06  本文已影响0人  Challis
import os
from threading import Thread, Timer
import time

lst = []


def my_timer(interval, file_path, file_timeout):
    def wrapper(fun):
        def inner(*args, **kwargs):
            print("定时器")
            if os.path.exists(file_path):
                write_time = os.stat(file_path).st_mtime
                print(f"文件最后写入时间{time.time() - write_time}")
                if time.time() - write_time >= file_timeout:
                    return 1
            # t = Thread(target=fun
            # fun()
            print(lst)
            if lst:
                t = lst[0]
            else:
                t = Thread(target=fun, args=args, kwargs=kwargs)
                t.setDaemon(True)
                lst.append(t)
                t.start()
            if t.is_alive():
                print("程序还在运行")
                t2 = Timer(interval, inner, args=args, kwargs=kwargs)
                t2.start()
                t2.join()
            else:
                print("程序运行完毕")
                return 0

        return inner
    return wrapper


def tlimit(limit_time):
    def outer(fun):
        def wrapper(*args, **kwargs):

            def raise_error():
                print("程序运行超时")
                return 2
            print("限制函数时间功能")
            timer = Timer(limit_time, raise_error)
            task = Thread(target=fun, args=args, kwargs=kwargs)
            task.setDaemon(True)
            print("任务开始")
            task.start()
            timer.start()

            while 1:
                if not task.is_alive():
                    print("超时函数运行完毕!!!")
                    timer.cancel()
                    return
                else:
                    print("超时函数仍在运行")
                time.sleep(1)

        return wrapper
    return outer


start_time = time.time()


@tlimit(30)
@my_timer(3, r"test.txt", 3)
def hello():
    for i in range(20):
        # print(i)
        time.sleep(1)
上一篇下一篇

猜你喜欢

热点阅读