Skip to main content
 首页 » 编程设计

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

2024年12月31日7think

我有一个几乎 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() 

希望这能满足您的需求。