在python里創(chuàng)建一個(gè)任務(wù)(Task)實(shí)例
與事件循環(huán)進(jìn)行交互,最基本的方式就是任務(wù),任務(wù)封裝了協(xié)程和自動(dòng)跟蹤它的狀態(tài)。任務(wù)是Future類的子類,所以其它協(xié)程可以等待任務(wù)完成,或當(dāng)這些任務(wù)完成獲取返回結(jié)果。
在這里通過create_task()函數(shù)來創(chuàng)建一個(gè)任務(wù)實(shí)例,然后事件循環(huán)就運(yùn)行這個(gè)任務(wù),直到這個(gè)任務(wù)返回為止:
import asyncio async def task_func(): print(’in task_func’) return ’the result’ async def main(loop): print(’creating task’) task = loop.create_task(task_func()) print(’waiting for {!r}’.format(task)) return_value = await task print(’task completed {!r}’.format(task)) print(’return value: {!r}’.format(return_value)) event_loop = asyncio.get_event_loop()try: event_loop.run_until_complete(main(event_loop))finally: event_loop.close()
結(jié)果輸出如下:
creating taskwaiting for <Task pending coro=<task_func() running at D:workcsdnpython_Game1exampleasyncio_create_task.py:4>>in task_functask completed <Task finished coro=<task_func() done, defined at D:workcsdnpython_Game1exampleasyncio_create_task.py:4> result=’the result’>return value: ’the result’
補(bǔ)充知識(shí):python里創(chuàng)建任務(wù)執(zhí)行一半時(shí)取消任務(wù)執(zhí)行
下例子來演示創(chuàng)建任務(wù)執(zhí)行一半時(shí)取消任務(wù)執(zhí)行,這時(shí)會(huì)拋出異常CancelledError,同時(shí)也提供了一個(gè)機(jī)會(huì)來刪除占用資源等等:
import asyncio async def task_func(): print(’in task_func, sleeping’) try: await asyncio.sleep(1) except asyncio.CancelledError: print(’task_func was canceled’) raise return ’the result’ def task_canceller(t): print(’in task_canceller’) t.cancel() print(’canceled the task’) async def main(loop): print(’creating task’) task = loop.create_task(task_func()) loop.call_soon(task_canceller, task) try: await task except asyncio.CancelledError: print(’main() also sees task as canceled’) event_loop = asyncio.get_event_loop()try: event_loop.run_until_complete(main(event_loop))finally: event_loop.close()
結(jié)果輸出如下:
creating taskin task_func, sleepingin task_cancellercanceled the tasktask_func was canceledmain() also sees task as canceled
以上這篇在python里創(chuàng)建一個(gè)任務(wù)(Task)實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. IntelliJ IDEA設(shè)置自動(dòng)提示功能快捷鍵的方法2. ASP.NET MVC使用jQuery ui的progressbar實(shí)現(xiàn)進(jìn)度條4. android H5本地緩存加載優(yōu)化的實(shí)戰(zhàn)5. PHP程序員簡(jiǎn)單的開展服務(wù)治理架構(gòu)操作詳解(二)6. IDEA一鍵完成格式化、去除無用引用、編譯的操作7. Python3 json模塊之編碼解碼方法講解8. 詳解如何使用Net將HTML簡(jiǎn)歷導(dǎo)出為PDF格式9. SpringBoot整合Redis的步驟10. PHP如何開啟Opcache功能提升程序處理效率

網(wǎng)公網(wǎng)安備