美文网首页
定时器和函数执行时间限制

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

作者: Challis | 来源:发表于2022-11-06 20:02 被阅读0次
    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)
    

    相关文章

      网友评论

          本文标题:定时器和函数执行时间限制

          本文链接:https://www.haomeiwen.com/subject/hkpvtdtx.html