首页 > 解决方案 > 使不同的线程循环

问题描述

我是线程方面的新手,我在同时运行 2 个线程和不同的睡眠时间时遇到问题。我所拥有的是:

def function(browser):
    sendemail()

def secondfunction(browser):
    sendemail_2()

if __name__ == "__main__":
 time=configs()
 while True:
  time=configs()
  if condition==True:
    x =threading.Thread(target=function,args=(browser,))
    x.start()
  if secondcondition==True:
    x =threading.Thread(target=function,args=(browser,))
    x.start()
  time.sleep(time)

两个不同的函数,在主线程中我做了一段时间为真,以便睡眠时间不断更新,然后当第一个条件返回 true 时,它​​开始,在函数内休眠并传递到现在将为 true 的第二个条件,再次运行线程,然后再次跳转到 time.sleep 的 while true 将有所不同并继续循环。我想要的是第二个线程,它将以“secondfunction”作为目标,每 5 分钟运行和睡眠一次,但如果我这样做:

if __name__ == "__main__":
 time=configs()
 while True:
  time=configs()
  if condition==True:
    x =threading.Thread(target=function,args=(browser,))
    x.start()
  if secondcondition==True:
    x =threading.Thread(target=function,args=(browser,))
    x.start()
  time.sleep(time)
 while True:
   y =threading.Thread(target=secondfunction,args=(browser,))
   y.start()
   time.sleep(300)

第一个当真有效,但不会让我的脚本在第二个当真时运行。我需要让一个线程休眠一段由“时间”变量定义的时间,同时第二个线程仍然每 5 分钟运行一次,两者都在具有不同休眠时间的循环中。我该怎么做?

标签: pythonmultithreading

解决方案


您可以为第二个无限循环创建一个单独的函数,并预先在单独的线程中调用它:

def second_function_loop():
  while True:
    secondfunction(browser)
    time.sleep(300)


if __name__ == "__main__":
  threading.Thread(target=second_function_loop).start()
  while True:
    time=configs()
    if condition:
      threading.Thread(target=function,args=(browser,)).start()
    if secondcondition:
      threading.Thread(target=function,args=(browser,)).start()
    time.sleep(time)

推荐阅读