Skip to main content

Gevent Runner

Gevent Runner — это инструмент для управления задачами на основе гринлетов (greenlets) в Python с использованием библиотеки gevent.

Возможности

  • ✅ Запуск нескольких конкурентных задач одновременно
  • ✅ Динамическое добавление и удаление задач в процессе работы
  • ✅ Корректная обработка сигналов завершения (SIGTERM, SIGINT)
  • ✅ Потокобезопасное управление задачами

Установка

Из исходников

pip install -e .

Для разработки

pip install -e ".[dev]"

Требования

  • Python >= 3.10
  • gevent == 24.11.1

Быстрый старт

Базовый пример

Создайте несколько задач и запустите их одновременно:

import time
import gevent
from classic.gevent_runner.runner import GreenletRunner


def print_numbers():
    count = 0
    while True:
        count += 1
        print(f"[Numbers Task] Count: {count}")
        gevent.sleep(2)


def print_timestamp():
    while True:
        current_time = time.strftime("%H:%M:%S")
        print(f"[Timestamp Task] Current time: {current_time}")
        gevent.sleep(3)


def print_heartbeat():
    while True:
        print(f"[Heartbeat Task] System is alive!")
        gevent.sleep(5)


def main():
    print("Starting GreenletRunner with 3 concurrent tasks...")
    print("Press Ctrl+C to stop all tasks\n")
    
    # Создаём экземпляр runner
    runner = GreenletRunner()
    
    # Добавляем задачи в runner
    runner.add(print_numbers, print_timestamp, print_heartbeat)
    
    # Запускаем главный цикл (блокирует выполнение до получения SIGTERM или SIGINT)
    runner.run()
    
    print("\nAll tasks stopped gracefully.")


if __name__ == "__main__":
    main()

Вывод:

Starting GreenletRunner with 3 concurrent tasks...
Press Ctrl+C to stop all tasks

[Numbers Task] Count: 1
[Timestamp Task] Current time: 12:34:56
[Numbers Task] Count: 2
[Heartbeat Task] System is alive!
[Timestamp Task] Current time: 12:34:59
...

Нажмите Ctrl+C для корректной остановки всех задач.

Использование

Создание runner

from classic.gevent_runner.runner import GreenletRunner

runner = GreenletRunner()

Добавление задач

Вы можете добавить одну или несколько задач одновременно:

# Добавление одной задачи
runner.add(my_task)

# Добавление нескольких задач
runner.add(task1, task2, task3)

# Добавление задачи с демоном
runner.add(task1, daemon=True)

Важно: Задача должна быть вызываемой функцией (callable). Каждая задача может быть добавлена только один раз.

Удаление задач

Остановка и удаление задач с опциональным таймаутом:

# Удаление одной задачи
runner.remove(my_task)

# Удаление нескольких задач с таймаутом
runner.remove(task1, task2, timeout=2.0)

При удалении задачи, гринлет будет корректно завершён.

Запуск runner

# Запуск основного цикла (блокирующий вызов)
runner.run()

Метод run() блокирует выполнение до получения сигнала SIGTERM или SIGINT (Ctrl+C).

Metadata

Release files for gevent-runner 0.0.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for gevent-runner 0.0.3
File Size Uploaded Provenance
gevent_runner-0.0.3.tar.gz 4.5 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for gevent-runner 0.0.3
File Interpreter ABI Platform
gevent_runner-0.0.3-py3-none-any.whl Python 3 none any Details

Total release size: 9.4 kB

Release files / gevent_runner-0.0.3.tar.gz

Download URL gevent_runner-0.0.3.tar.gz
Size 4.5 kB
Tags Source
SHA-256 checksum
How to use checksums
65c2fe4a45de3b94ad69970bd65d45cc811f94a9705f784675cf642b36754d62
BLAKE2b-256 checksum
How to use checksums
21b9f5fa5e1542561081ba8aab2d0bbf0e52c0711fcaa674d92f07e5bc38c951
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.10.13

Release files / gevent_runner-0.0.3-py3-none-any.whl

Download URL gevent_runner-0.0.3-py3-none-any.whl
Size 4.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d4890043c3e78da59323497f2c81b4ffa479da0e31d8a69d44f0e8db0074e59a
BLAKE2b-256 checksum
How to use checksums
7d10cbe4e5e0c68f5500358edde7abe9d30dff2489b871f00e098ec0656ddf22
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.10.13

Security for gevent-runner 0.0.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page