akrisanov
7/21/2018 - 1:56 AM

Python Async Examples

Python Async Examples

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()
    
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 time 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 eventlet import sleep

def hello():
    sleep(3)
    print('Hello!')

if __name__ == '__main__':
    hello()
    
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())
    
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()

async def hello():
    await asyncio.sleep(3)
    print('Hello!')
    
if __name__ == '__main__':
    loop.run_until_complete(hello())