Skip to content

Instantly share code, notes, and snippets.

@virus-warnning
Last active December 21, 2018 17:05
Show Gist options
  • Save virus-warnning/ebd830cd4ad6f34e47e5ccd03082c9ff to your computer and use it in GitHub Desktop.
Save virus-warnning/ebd830cd4ad6f34e47e5ccd03082c9ff to your computer and use it in GitHub Desktop.
用管理學的 PDCA 循環理解 Python 3.7 的非同步處理
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()
@virus-warnning
Copy link
Author

virus-warnning commented Dec 21, 2018

Output

Join the team.
(Plan B) -> Delay -> Cancel -> Apologize (Bad mood: 1)
(Plan B, Plan C, Plan A) -> Do -> Check -> Act (Bad mood: 1)
(Plan B, Plan C) -> Delay -> Cancel -> Apologize (Bad mood: 2)
(Plan B, Plan C) -> Delay -> Cancel -> Apologize (Bad mood: 3)
(Plan A, Plan B, Plan C) -> Do -> Check -> Act (Bad mood: 3)
(Plan A, Plan C) -> Delay -> Cancel -> Apologize (Bad mood: 4)
(Plan C, Plan B) -> Delay -> Cancel -> Apologize (Bad mood: 5)
Leave the team.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment