在python里创建一个任务(Task)实例
与事件循环进行交互,最基本的方式就是任务,任务封装了协程和自动跟踪它的状态。任务是Future类的子类,所以其它协程可以等待任务完成,或当这些任务完成获取返回结果。
在这里通过create_task()函数来创建一个任务实例,然后事件循环就运行这个任务,直到这个任务返回为止:
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()
结果输出如下:
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’
补充知识:python里创建任务执行一半时取消任务执行
下例子来演示创建任务执行一半时取消任务执行,这时会抛出异常CancelledError,同时也提供了一个机会来删除占用资源等等:
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()
结果输出如下:
creating taskin task_func, sleepingin task_cancellercanceled the tasktask_func was canceledmain() also sees task as canceled
以上这篇在python里创建一个任务(Task)实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持好吧啦网。
相关文章:
1. IntelliJ IDEA设置条件断点的方法步骤2. Python使用oslo.vmware管理ESXI虚拟机的示例参考3. IDEA的Mybatis Generator驼峰配置问题4. javascript设计模式 ? 建造者模式原理与应用实例分析5. Java构建JDBC应用程序的实例操作6. Express 框架中使用 EJS 模板引擎并结合 silly-datetime 库进行日期格式化的实现方法7. 一篇文章带你了解JavaScript-对象8. IntelliJ Idea2017如何修改缓存文件的路径9. Jsp中request的3个基础实践10. 浅谈SpringMVC jsp前台获取参数的方式 EL表达式
