python - 如何正确安排 while 函数被中断并调用另一个函数

标签 python python-3.x while-loop scheduled-tasks thread-synchronization

我有一个几乎 24/7 全天候运行的脚本。我希望它每天被适本地打断几次。

from time import sleep

def function_one():
    while True:
        print("I'm working 24/7 and doing some important stuff here!")
        print("Very important!")
        sleep(5)

def function_two():
    print("I just need to do my job once, however, function_one should be stopped while i'm working!")    

我希望 function_one 每 3 小时被中断一次(在循环之间),然后 function_two 被调用一次,紧接着 function_one 应该继续工作。

这样做的正确方法是什么?

最佳答案

为什么不将对函数 2 的调用放在函数 1 本身中。这样它会等到函数 2 运行后再恢复函数 1。像这样:

from __future__ import generators
from time import sleep
import time

def function_one():
    while True:
        print("I'm working 24/7 and doing some important stuff here!")
        print("Very important!")
        #First bit checks whether the hour is divisible by 3 (every 3 hours)
                                                #This bit checks that the minute and seconds combined are the first 5 seconds of the hour
        if int(time.strftime("%H"))%3 == 0 and int(time.strftime("%M%S")) < 6:
            #Calls function 2 and won't resume until function 2 is finished
            function_two()
            print("That was the 2 second wait from function 2")
        sleep(5)

def function_two():
    print("I just need to do my job once, however, function_one should be stopped while i'm working!")
    sleep(2)

function_one()

希望这能满足您的需求。

关于python - 如何正确安排 while 函数被中断并调用另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51211446/

相关文章:

python - 通过HTTP的Python网络摄像头图像服务器未显示图像

python - Mad lib Python,为什么下面的循环不能正常工作?

python - 如何对数据集中的某些单词进行值计数

python - Numpy 数组、幂运算符、错误的值/符号

Python 3,尝试登录facebook并获取源代码

python - 安装Python 3.8.1 --with-openssl --without-root/apt/yum

python - 在Python中组合字典中列表的所有排列

java - 需要在类中实现do、while循环

java - 无法访问 while 循环内初始化的数组

python - 返回多个 "while"循环结果