python - 使不同的线程循环
问题描述
我是线程方面的新手,我在同时运行 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 分钟运行一次,两者都在具有不同休眠时间的循环中。我该怎么做?
解决方案
您可以为第二个无限循环创建一个单独的函数,并预先在单独的线程中调用它:
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)
推荐阅读
- android - 为什么 PackageManager.queryIntentActivities 方法只返回 ACTION_VIEW 的默认浏览器信息?
- javascript - 有没有办法修改 FullCalendar 4 中的多日事件以显示为这样?
- python - 如何创建一个接受字典输入的函数?
- sql - oracle sql中唯一和重复的Sql查询?
- tensorflow - 如何从 .cfg 文件加载暗网 YOLOv3 模型并从 .weights 文件加载权重,并将带有权重的模型保存到 .h5 文件?
- ruby-on-rails - Rails 默认行为:为什么 Rails 默认不生成不同的 Etag 或返回 304 Not Modified?
- operating-system - 不是特定于操作系统的库是否实际上使用了它们正在运行的操作系统的 API?
- c# - 如何在c#中将格鲁吉亚日历转换为波斯日历
- ansible - 无法在 Ansible Playbook 中包含包含变量的文件
- r - 在 R 中定义自定义日期