Skip to content

Instantly share code, notes, and snippets.

@miguelgrinberg
Created February 20, 2017 00:43
Show Gist options
  • Save miguelgrinberg/f15bc03471f610cfebeba62438435508 to your computer and use it in GitHub Desktop.
Save miguelgrinberg/f15bc03471f610cfebeba62438435508 to your computer and use it in GitHub Desktop.
async examples
import asyncio
loop = asyncio.get_event_loop()
async def hello():
await asyncio.sleep(3)
print('Hello!')
if __name__ == '__main__':
loop.run_until_complete(hello())
import asyncio
loop = asyncio.get_event_loop()
def hello():
loop.call_later(3, print_hello)
def print_hello():
print('Hello!')
loop.stop()
if __name__ == '__main__':
loop.call_soon(hello)
loop.run_forever()
import asyncio
loop = asyncio.get_event_loop()
@asyncio.coroutine
def hello():
yield from asyncio.sleep(3)
print('Hello!')
if __name__ == '__main__':
loop.run_until_complete(hello())
from eventlet import sleep
def hello():
sleep(3)
print('Hello!')
if __name__ == '__main__':
hello()
from gevent import sleep
def hello():
sleep(3)
print('Hello!')
if __name__ == '__main__':
hello()
from time import sleep
def hello():
sleep(3)
print('Hello!')
if __name__ == '__main__':
hello()
from twisted.internet import reactor
def hello():
reactor.callLater(3, print_hello)
def print_hello():
print('Hello!')
reactor.stop()
if __name__ == '__main__':
reactor.callWhenRunning(hello)
reactor.run()
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks, Deferred
def sleep(secs):
d = Deferred()
reactor.callLater(secs, d.callback, None)
return d
@inlineCallbacks
def hello():
yield sleep(3)
print('Hello!')
reactor.stop()
if __name__ == '__main__':
reactor.callWhenRunning(hello)
reactor.run()
@kooky
Copy link

kooky commented Jul 4, 2017

I'd love an example of these with some loops

@shamhub
Copy link

shamhub commented Jul 13, 2017

@zhaowb
Copy link

zhaowb commented May 2, 2018

@kooky
Hope this can help

import gevent
from gevent import sleep
def hello():
    print('Hello')
    sleep(3)
    print('World')

jobs = [gevent.spawn(hello) for i in range(10)]
gevent.wait(jobs)

@jian-en
Copy link

jian-en commented May 7, 2018

@kooky

import asyncio

async def factorial(name, number):
f = 1
for i in range(2, number+1):
print("Task %s: Compute factorial(%s)..." % (name, i))
await asyncio.sleep(1)
f *= i
print("Task %s: factorial(%s) = %s" % (name, number, f))

loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(
factorial("A", 2),
factorial("B", 3),
factorial("C", 4),
))
loop.close()

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