操作系统世界历险记

cooolr 于 2022-05-16 发布

第一天: 保持清醒

# -*- coding: utf-8 -*-

import time
import random
import asyncio

def callback():
    '''
    中断处理程序
    '''
    print(f"[{time.ctime()[11:19]}] - 感应呼吸")

async def breath(start, end):
    '''
    呼吸程序,假定一次呼吸4到7秒
    Args:
        start (int): 最短呼吸时长
        end (int): 最长呼吸时长
    '''
    await asyncio.sleep(random.uniform(start, end))

async def make_breath():
    '''
    呼吸驱动,每次呼吸完成调用中断处理程序
    '''
    while True:
        await breath(4, 7)
        callback()


async def do_somthing(something, duration, breathe):
    '''
    做事程序,做什么事情都要保持呼吸
    Args:
        something (str): 做某事
        duration (int): 持续时长
        breathe (asyncio.Task): 呼吸驱动,事情完成后结束
    '''
    print(f"[{time.ctime()[11:19]}] - 正在{something}")
    await asyncio.sleep(duration)
    breathe.cancel()
    print(f"[{time.ctime()[11:19]}] - {something}完成")

def main():
    '''
    调度程序
    '''
    loop = asyncio.get_event_loop()
    breathe = loop.create_task(make_breath())
    todo = do_somthing('发呆', 30, breathe)
    loop.run_until_complete(asyncio.wait([breathe, todo]))
    loop.close()

if __name__ == '__main__':
    main()

输出

[13:27:39] - 正在发呆
[13:27:44] - 感应呼吸
[13:27:50] - 感应呼吸
[13:27:57] - 感应呼吸
[13:28:03] - 感应呼吸
[13:28:08] - 感应呼吸
[13:28:09] - 发呆完成

活不过第一天,卒。