在python里创建一个任务(Task)实例
2020-04-26 07:05
796 查看
与事件循环进行交互,最基本的方式就是任务,任务封装了协程和自动跟踪它的状态。任务是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 task
waiting for <Task pending coro=<task_func() running at D:\work\csdn\python_Game1\example\asyncio_create_task.py:4>>
in task_func
task completed <Task finished coro=<task_func() done, defined at D:\work\csdn\python_Game1\example\asyncio_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 task
in task_func, sleeping
in task_canceller
canceled the task
task_func was canceled
main() also sees task as canceled
以上这篇在python里创建一个任务(Task)实例就是小编分享给大家的全部内容了,希望能给大家一个参考
您可能感兴趣的文章:
相关文章推荐
- python里创建一个任务(Task)
- Android程序 类QQ通知常驻在Notification栏 点击Notification正确回调到之前已经放置在后台的Task中的对应Activity,而不是创建它的一个新实例
- 【Python】一个python实例:给重要的文件创建备份.摘自crossin-python简明教程
- Android程序 类QQ通知常驻在Notification栏 点击Notification正确回调到之前已经放置在后台的Task中的对应Activity,而不是创建它的一个新实例
- python 创建一个空dataframe 然后添加行数据的实例
- python实例1:创建一个登陆模块
- Python创建二维数组实例(关于list的一个小坑)
- python实例1:创建一个登陆模块
- Android程序 类QQ通知常驻在Notification栏 点击Notification正确回调到之前已经放置在后台的Task中的对应Activity,而不是创建它的一个新实例
- 点击Notification正确回调到之前已经放置在后台的Task中的对应Activity,而不是创建它的一个新实例
- Android程序 类QQ通知常驻在Notification栏 点击Notification正确回调到之前已经放置在后台的Task中的对应Activity,而不是创建它的一个新实例
- 使用事件处理创建一个简单的绘图实例程序 python
- Python创建一个元素都为0的列表实例
- python判断文件是否存在,不存在就创建一个的实例
- Android程序 类QQ通知常驻在Notification栏 点击Notification正确回调到之前已经放置在后台的Task中的对应Activity,而不是创建它的一个新实例
- python实例1:创建一个登陆模块
- 【java梗系列】搞一个从外边无法创建实例的单例类(安全单例)
- 一个简单的springMVC的定时任务实例
- python如何为创建大量实例节省内存
- Python3基础 __str__ print一个类的实例对象的时候 使用的魔法方法