跳转到主要内容

异步任务调度器(用于管理后台任务)

项目描述

https://travis-ci.org/aio-libs/aiojobs.svg?branch=master https://codecov.io/gh/aio-libs/aiojobs/branch/master/graph/badge.svg https://img.shields.io/pypi/v/aiojobs.svg Documentation Status Chat on Gitter

异步任务调度器(用于管理后台任务)

该库提供了一种受控的方式来为asyncio应用程序调度后台任务。

安装

$ pip3 install aiojobs

使用示例

import asyncio
import aiojobs

async def coro(timeout):
    await asyncio.sleep(timeout)

async def main():
    async with aiojobs.Scheduler() as scheduler:
        for i in range(100):
            # spawn jobs
            await scheduler.spawn(coro(i/10))

        await asyncio.sleep(5.0)
        # not all scheduled jobs are finished at the moment
    # Exit from context will gracefully wait on tasks before closing
    # any remaining spawned jobs

asyncio.run(main())

使用调度器保护任务

通常建议使用 asyncio.shield 来保护任务不被取消。然而,内部受保护的任务无法跟踪,因此在应用程序关闭期间存在被取消的风险。

为了解决这个问题,aiojobs 包含一个 aiojobs.Scheduler.shield 方法来屏蔽任务,同时在调度器中跟踪它们。结合 aiojobs.Scheduler.wait_and_close 方法,这允许在应用程序关闭期间,屏蔽的任务有足够的时间成功完成。

例如:

import asyncio
import aiojobs
from contextlib import suppress

async def important():
    print("START")
    await asyncio.sleep(5)
    print("DONE")

async def run_something(scheduler):
    # If we use asyncio.shield() here, then the task doesn't complete and DONE is never printed.
    await scheduler.shield(important())

async def main():
    async with aiojobs.Scheduler() as scheduler:
        t = asyncio.create_task(run_something(scheduler))
        await asyncio.sleep(0.1)
        t.cancel()
        with suppress(asyncio.CancelledError):
            await t

asyncio.run(main())

与 aiohttp.web 的集成

from aiohttp import web
from aiojobs.aiohttp import setup, spawn

async def handler(request):
    await spawn(request, coro())
    return web.Response()

app = web.Application()
app.router.add_get('/', handler)
setup(app)

或只需

from aiojobs.aiohttp import atomic

@atomic
async def handler(request):
    return web.Response()

有关更多信息,请参阅文档:https://aiojobs.readthedocs.io

交流渠道

aio-libs Google 群组:https://groups.google.com/forum/#!forum/aio-libs

请随时在此处发布您的问题和想法。

Gitter Chat https://gitter.im/aio-libs/Lobby

我们支持 Stack Overflow。请在那里的问题中添加 python-asyncioaiohttp 标签。

作者和许可证

aiojobs 包由 Andrew Svetlov 编写。

它是 Apache 2 许可的,并且可以免费获取。

项目详情


下载文件

下载您平台上的文件。如果您不确定选择哪个,请了解更多关于 安装包 的信息。

源代码分发

aiojobs-1.3.0.tar.gz (138.9 kB 查看哈希)

上传时间 源代码

构建分发

aiojobs-1.3.0-py3-none-any.whl (9.5 kB 查看哈希)

上传时间 Python 3

由以下支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误记录 StatusPage StatusPage 状态页面