Skip to main content

An abstract class for asyncio services that run in their dedicated threads.

Project description

aioservicethread

An abstract class for asyncio services that run in their dedicated threads.

Installation

pip install aioservicethread

Examples

Running multiple services

This example shows running multiple services in dedicated threads. When the server needs to shut down, each service can execute its graceful shutdown procedures.

import asyncio
import logging
import time

from aioservicethread import AioServiceThread

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# ...


class MyServer(AioServiceThread):
    port: int

    def __init__(self, name: str = "server-1", port: int = 8080):
        super().__init__(name=name)
        self.port = port

    async def serve_forever(self):
        while True:
            await asyncio.sleep(3600)

    async def _arun(self):
        self.service_running.set()
        self.log(f"started on port {self.port}")

        # start serving
        task1 = asyncio.create_task(self.serve_forever())

        # wait for the stop event
        await self._astop_event.wait()

        # gracefully shut down the server
        self.log("stopping")

        task1.cancel()
        try:
            await task1
        except asyncio.CancelledError:
            pass

        self.log("done")


# ...


def main():
    server1 = MyServer("server-1", port=8080)
    server2 = MyServer("server-2", port=8181)

    logger.info("starting services ...")

    server1.start()
    server2.start()

    # serve until stopped
    print("Press Ctrl-C to exit")
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print(" shutting down")

    logger.info("stopping services")

    server1.stop_and_join()
    server2.stop_and_join()

    logger.info("done")


if __name__ == "__main__":
    main()

Output:

INFO:__main__:starting services ...
INFO:MyServer.server-2:started on port 8181
Press Ctrl-C to exit
INFO:MyServer.server-1:started on port 8080
^C shutting down
INFO:__main__:stopping services
INFO:MyServer.server-1:stopping
INFO:MyServer.server-1:done
INFO:MyServer.server-2:stopping
INFO:MyServer.server-2:done
INFO:__main__:done

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distribution

aioservicethread-0.2.0-py3-none-any.whl (5.8 kB view details)

Uploaded Python 3

File details

Details for the file aioservicethread-0.2.0-py3-none-any.whl.

File metadata

File hashes

Hashes for aioservicethread-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 aeefd9fc585ad428abe5745b58b0376279cd9c48da1790f166122f2ab384ae99
MD5 7d651f7ef3c482368a1c1095f40189bf
BLAKE2b-256 60a7d7d63d18cbfea45b8c02842ea678cf3fa2e90e0fc2f9e209c97bf7fcb781

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page