在给定的 x 时间内循环一个 python 函数

Loop a python function by given x time

提问人:DARK SOUL 提问时间:11/4/2023 最后编辑:cconsta1DARK SOUL 更新时间:11/4/2023 访问量:64

问:

在下面的功能中,在我手动终止它之前不会停止。我需要知道一种在 10 秒后终止函数并自动终止它的方法。然后我想再次运行它(循环)。my_module

import time
import my_module

def my_function():
    c= 1
    while True:
        my_module
my_function()

我尝试过穿线,但找不到方法。

python-3.x 多线程 循环 python-multithreading

评论

0赞 Goku - stands with Palestine 11/4/2023
您可以使用然后退出time.sleep(10)
0赞 Tsyvarev 11/4/2023
这回答了你的问题吗?函数调用超时

答:

0赞 Behtash 11/4/2023 #1

您可以使用多种方法,但它们可能不合理。这些事情在我脑海中浮现:

  1. 您可以在 python 中有一个基本模块,并使用 os 库运行此文件 python 模块:os.system(“python yourFile.py”) 并在 for 循环或 while
  2. 使用类:在类中实现my_function,在使用该类结束时尝试调用 __ del __(self),引用:构造函数和析构函数
  3. 尝试使用 cronjob 或制作 bat 或 bash 脚本设置计时器并尝试运行您的模块
  4. 尝试使用多线程:
import time
import threading

second =0
def timer():
   global second
   while True:
      time.sleep(1)
      second +=1

def module_function():
    
   while second<=10:
      print("hi")
   print("finish")
    

t1 = threading.Thread(target=module_function  )
t2 = threading.Thread(target=timer  )
t1.start()
t2.start()
1赞 mandy8055 11/4/2023 #2

就我正确理解您的要求而言;您需要一种方法,无论该模块的执行状态如何,都可以在 10 秒后自动终止模块执行。如果模块处于某个执行之间,则也停止其执行。如果这是您的要求,那么您可以尝试:

import time
import threading
import my_module

def my_function(stop_event):
  while not stop_event.is_set():
    my_module
# Loop to run the function again
while True:
  stop_event = threading.Event()
  t = threading.Thread(target=my_function, args=(stop_event,))
  t.start()
  time.sleep(10)  # Let the function run for 10 seconds
  stop_event.set()  # Signal the function to stop
  t.join()

代码演示