1. 程式人生 > 程式設計 >在python裡建立一個任務(Task)例項

在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 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)例項就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。