Last active
December 21, 2018 17:05
-
-
Save virus-warnning/ebd830cd4ad6f34e47e5ccd03082c9ff to your computer and use it in GitHub Desktop.
用管理學的 PDCA 循環理解 Python 3.7 的非同步處理
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
import asyncio | |
class PDCACycle: | |
def __init__(self): | |
self.bad_mood = 0 | |
self.interval = 1 | |
async def plan(self, name): | |
await asyncio.sleep(random.random() * 1.2) | |
return 'Plan {}'.format(name) | |
async def do(self): | |
(done, pending) = await asyncio.wait([ | |
self.plan('A'), | |
self.plan('B'), | |
self.plan('C') | |
], timeout=1.0) | |
plans = [] | |
for task in done: | |
plans.append(task.result()) | |
print('({}) -> '.format(', '.join(plans)), end='', flush=True) | |
await asyncio.sleep(self.interval) | |
delayed = len(done) < 3 | |
if delayed: | |
print('Delay -> ', end='', flush=True) | |
else: | |
print('Do -> ', end='', flush=True) | |
await asyncio.sleep(self.interval) | |
return delayed | |
async def check(self): | |
delayed = await self.do() | |
if delayed: | |
print('Cancel -> ', end='', flush=True) | |
else: | |
print('Check -> ', end='', flush=True) | |
await asyncio.sleep(self.interval) | |
return delayed | |
async def act(self): | |
canceled = await self.check() | |
if canceled: | |
print('Apologize', end='', flush=True) | |
self.bad_mood += 1 | |
else: | |
print('Act', end='', flush=True) | |
return | |
def run(self, threshold): | |
print('Join the team.') | |
while self.bad_mood < threshold: | |
asyncio.run(self.act()) | |
print(' (Bad mood: {})'.format(self.bad_mood)) | |
print('Leave the team.') | |
def main(): | |
cycle = PDCACycle() | |
cycle.run(5) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output