※当サイトの記事には、広告・プロモーションが含まれます。

Pythonで定期実行が実現できるライブラリは、どんなものがあるのか

gigazine.net

ウェブカメラの普及やオンライン会議アプリの流行に加え、新型コロナウイルスのパンデミックによる対面会議を避ける風潮により、自宅にいながらオンラインで会議を行うバーチャル会議も現代では一般的になっています。

人類初のバーチャル会議は1916年に開催、どれくらいの規模でどのように開催されたのか? - GIGAZINE

アメリカに本部を置く電気・情報工学分野の学術研究団体であるIEEEによると、バーチャル会議の原初とされるのはIEEEの前身であるアメリカ電気技術者協会(AIEE)が1916年に開催した会議であるそうです。当時どのようにバーチャル会議が実施されたのかなどの詳細について、サウスカロライナ大学の教授であるアリソン・マーシュ氏が解説しています。

人類初のバーチャル会議は1916年に開催、どれくらいの規模でどのように開催されたのか? - GIGAZINE

⇧ 今が2024年なので、108年前になるのか、驚きですな...

アトランタの地元紙はAIEEの会議を「世界史上かつて達成されたことのない偉業」と称賛しました。また、フィラデルフィアの日刊紙は「この電話回線は20州にまたがり、約6500kmを横断し、5000個のスイッチを経由する15万0000本以上の電柱によって支えられました」と説明しています。

人類初のバーチャル会議は1916年に開催、どれくらいの規模でどのように開催されたのか? - GIGAZINE

マーシュ氏によると、AIEEの世界初バーチャル会議が驚異的だった理由のひとつは、その時期にあります。最初の大陸横断電話が完成したのは1914年6月17日で、通話が実現したのはサンフランシスコ万国博覧会の祝賀会と同日の1915年1月25日でした。「そこからわずか1年で、8都市を結んで5000人が参加するバーチャル会議を実現したことは、注目に値します」とマーシュ氏は述べています。

人類初のバーチャル会議は1916年に開催、どれくらいの規模でどのように開催されたのか? - GIGAZINE

⇧ 時期的には、

第一次世界大戦(だいいちじせかいたいせん、英: World War I,The great war、略称:WWI、WW1)は、1914年(大正3年)7月28日から1918年(大正7年)11月11日にかけて、連合国と中央同盟国間で行われた世界規模の戦争である。

第一次世界大戦 - Wikipedia

⇧「第一次世界大戦」と同じと。

Pythonで定期実行が実現できるライブラリは、どんなものがあるのか

ChatGPTに質問してみたところ、全部で10個のライブラリがあるという回答が返ってきた。

  1. sched ← Python標準のライブラリ
  2. APScheduler
  3. schedule
  4. Celery
  5. APScheduler (Async)
  6. Airflow
  7. croniter
  8. joblib
  9. RQS (Redis Queue Scheduler)
  10. Twisted (task.deferLater)

「2. APScheduler」と「5. APScheduler (Async)」が別物なのかは疑問だが...

各々の特徴については、以下のような回答が返ってきた。

No ライブラリ名 説明
① サポートされるスケジュール形式
② 並行処理のサポート
③ 高度なスケジュール設定
④ 非同期処理のサポート
➄ 使用方法/適用例
⑥ 備考
1 sched ① インターバル(間隔指定)
② サポートしない
③ 手動で日時を計算(例: 毎日9時)
④ サポートしない
➄ シンプルなタスクスケジューリングに使用
⑥ Python標準ライブラリ。シンプルで軽量だが、柔軟性に欠ける
2 APScheduler ① Cron形式(cron式)、インターバル、日時指定
② サポート(複数スレッド/プロセス)
③ 高度な日時指定(毎週、毎月、特定日時など)
④ サポート
➄ 高度なスケジュール設定、バックグラウンドタスクに適用
⑥ 高機能なスケジューラー。Cron形式がサポートされる。
3 schedule ① インターバル(分、時間、日など)
② サポートしない
③ 手動で日時を計算(例: 毎日9時)
④ サポートしない
➄ シンプルで軽量。手軽にタスクスケジュール
⑥ Pythonのシンプルなライブラリ。設定が簡単だが柔軟性に欠ける
4 Celery ① 定期実行(beat機能)、タスクの遅延実行
② サポート(分散型)
③ 複雑なスケジュール、遅延タスク
④ サポート
➄ 分散処理、バックグラウンドタスク、大規模システムでの使用
⑥ 分散型で大規模システム向け。設定が複雑だが強力。
5 APScheduler (Async) ① Cron形式(cron式)、インターバル、日時指定
② サポート(非同期タスク)
③ 高度な日時指定(非同期)
④ サポート
➄ 非同期処理のタスクを含む高度なスケジューリングに適用
⑥ 非同期タスク対応版APScheduler。非同期I/O操作が必要な場合に有効
6 Airflow ① DAG(有向非巡回グラフ)形式のタスク定義
② サポート(分散型)
③ 非常に高度なスケジュール設定
④ サポート
➄ 複雑なワークフロー管理、大規模なバッチ処理に適用
⑥ ワークフロー管理ツール。高度な依存関係管理や分散タスクに適応
7 croniter ① Cron式(cron式)
② サポートしない
③ Cron式でスケジュール指定可能
④ サポートしない
➄ Cron形式のスケジュールを処理するライブラリ
⑥ Cron式スケジュールの解析と計算に特化。
8 joblib ① インターバル(間隔指定)
② サポートしない
③ 手動で日時を計算(例: 毎日9時)
④ サポートしない
➄ 分散並列処理、データ処理の高速化、バッチ処理に使用
⑥ 並列処理向けで、スケジュール機能はサポートが薄いが高速な並列処理
9 RQS (Redis Queue Scheduler) ① タイマーやキューによるタスク定期実行
② サポート(分散型)
③ 高度なスケジュール設定(キュー管理)
④ サポート
➄ Redisバックエンドを使ったタスクスケジューリング
⑥ Redisを使った分散型のスケジュールシステム
10 Twisted (task.deferLater) ① 任意の時間後、定期実行、間隔指定
② サポート(並列、非同期)
③ 柔軟な設定
④ サポート(非同期対応)
➄ 非同期イベント駆動型プログラムにおける定期実行。リアルタイムシステム。
⑥ 非同期、イベント駆動型。複雑な非同期システムには非常に適している。

 

一般的な定期実行の実現方式って、どんなものがあるんでしたっけ?

大きく分けると、

  1. 無限ループ (Polling)
  2. スケジュール (Scheduled Tasks)
  3. イベント駆動型 (Event-driven)
  4. キュー駆動型 (Queue-driven)
  5. 遅延実行 (Delayed Execution)
  6. 時間同期型 (Time-Sync)
  7. 条件付き実行 (Conditional Execution)

上記の方式に大別されるらしい。

ただ、「スケジュール (Scheduled Tasks)」の方式であっても内部では「無限ループ」を利用してるっぽい気がしていて、Pythonの標準ライブラリの「sched」の処理を覗いてみたところ、

github.com

■https://github.com/python/cpython/blob/main/Lib/sched.py

"""A generally useful event scheduler class.

Each instance of this class manages its own queue.
No multi-threading is implied; you are supposed to hack that
yourself, or use a single instance per application.

Each instance is parametrized with two functions, one that is
supposed to return the current time, one that is supposed to
implement a delay.  You can implement real-time scheduling by
substituting time and sleep from built-in module time, or you can
implement simulated time by writing your own functions.  This can
also be used to integrate scheduling with STDWIN events; the delay
function is allowed to modify the queue.  Time can be expressed as
integers or floating-point numbers, as long as it is consistent.

Events are specified by tuples (time, priority, action, argument, kwargs).
As in UNIX, lower priority numbers mean higher priority; in this
way the queue can be maintained as a priority queue.  Execution of the
event means calling the action function, passing it the argument
sequence in "argument" (remember that in Python, multiple function
arguments are be packed in a sequence) and keyword parameters in "kwargs".
The action function may be an instance method so it
has another way to reference private data (besides global variables).
"""

import time
import heapq
from collections import namedtuple
from itertools import count
import threading
from time import monotonic as _time

__all__ = ["scheduler"]

Event = namedtuple('Event', 'time, priority, sequence, action, argument, kwargs')
Event.time.__doc__ = ('''Numeric type compatible with the return value of the
timefunc function passed to the constructor.''')
Event.priority.__doc__ = ('''Events scheduled for the same time will be executed
in the order of their priority.''')
Event.sequence.__doc__ = ('''A continually increasing sequence number that
    separates events if time and priority are equal.''')
Event.action.__doc__ = ('''Executing the event means executing
action(*argument, **kwargs)''')
Event.argument.__doc__ = ('''argument is a sequence holding the positional
arguments for the action.''')
Event.kwargs.__doc__ = ('''kwargs is a dictionary holding the keyword
arguments for the action.''')

_sentinel = object()

class scheduler:

    def __init__(self, timefunc=_time, delayfunc=time.sleep):
        """Initialize a new instance, passing the time and delay
        functions"""
        self._queue = []
        self._lock = threading.RLock()
        self.timefunc = timefunc
        self.delayfunc = delayfunc
        self._sequence_generator = count()

    def enterabs(self, time, priority, action, argument=(), kwargs=_sentinel):
        """Enter a new event in the queue at an absolute time.

        Returns an ID for the event which can be used to remove it,
        if necessary.

        """
        if kwargs is _sentinel:
            kwargs = {}

        with self._lock:
            event = Event(time, priority, next(self._sequence_generator),
                          action, argument, kwargs)
            heapq.heappush(self._queue, event)
        return event # The ID

    def enter(self, delay, priority, action, argument=(), kwargs=_sentinel):
        """A variant that specifies the time as a relative time.

        This is actually the more commonly used interface.

        """
        time = self.timefunc() + delay
        return self.enterabs(time, priority, action, argument, kwargs)

    def cancel(self, event):
        """Remove an event from the queue.

        This must be presented the ID as returned by enter().
        If the event is not in the queue, this raises ValueError.

        """
        with self._lock:
            self._queue.remove(event)
            heapq.heapify(self._queue)

    def empty(self):
        """Check whether the queue is empty."""
        with self._lock:
            return not self._queue

    def run(self, blocking=True):
        """Execute events until the queue is empty.
        If blocking is False executes the scheduled events due to
        expire soonest (if any) and then return the deadline of the
        next scheduled call in the scheduler.

        When there is a positive delay until the first event, the
        delay function is called and the event is left in the queue;
        otherwise, the event is removed from the queue and executed
        (its action function is called, passing it the argument).  If
        the delay function returns prematurely, it is simply
        restarted.

        It is legal for both the delay function and the action
        function to modify the queue or to raise an exception;
        exceptions are not caught but the scheduler's state remains
        well-defined so run() may be called again.

        A questionable hack is added to allow other threads to run:
        just after an event is executed, a delay of 0 is executed, to
        avoid monopolizing the CPU when other threads are also
        runnable.

        """
        # localize variable access to minimize overhead
        # and to improve thread safety
        lock = self._lock
        q = self._queue
        delayfunc = self.delayfunc
        timefunc = self.timefunc
        pop = heapq.heappop
        while True:
            with lock:
                if not q:
                    break
                (time, priority, sequence, action,
                 argument, kwargs) = q[0]
                now = timefunc()
                if time > now:
                    delay = True
                else:
                    delay = False
                    pop(q)
            if delay:
                if not blocking:
                    return time - now
                delayfunc(time - now)
            else:
                action(*argument, **kwargs)
                delayfunc(0)   # Let other threads run

    @property
    def queue(self):
        """An ordered list of upcoming events.

        Events are named tuples with fields for:
            time, priority, action, arguments, kwargs

        """
        # Use heapq to sort the queue rather than using 'sorted(self._queue)'.
        # With heapq, two events scheduled at the same time will show in
        # the actual order they would be retrieved.
        with self._lock:
            events = self._queue[:]
        return list(map(heapq.heappop, [events]*len(events)))    

⇧「無限ループ」っぽいことやってるのよね...

Pythonの標準ライブラリ「sched」で定期実行する場合は、「time」、「threading」などを併用する感じになるっぽい

大量データの処理や、複数のタスクの同期を制御するような状況では、利用が難しそうなのだが、簡易的なタスクスケジューラーとしての用途であるならば、Pythonの標準ライブラリ「sched」というものが用意されていますと。

docs.python.org

⇧ 公式のドキュメントによりますと、

『バージョン 3.3 で変更: scheduler クラスをマルチスレッド環境で安全に使用出来るようになりました。』

とあるので、「threading」も併用していく感じになるのかなと。

docs.python.org

⇧ 公式のドキュメントによりますと、

『CPython 実装の詳細: CPython は Global Interpreter Lock のため、ある時点で Python コードを実行できるスレッドは1つに限られます (ただし、いくつかのパフォーマンスが強く求められるライブラリはこの制限を克服しています)。アプリケーションにマルチコアマシンの計算能力をより良く利用させたい場合は、 multiprocessing モジュールや concurrent.futures.ProcessPoolExecutor の利用をお勧めします。 ただし、I/Oバウンドなタスクを並行して複数走らせたい場合においては、 マルチスレッドは正しい選択肢です。』

とあり、「機械学習」や「深層学習」とかのような用途においては、更に

  • multiprocessing
  • concurrent.futures.ProcessPoolExecutor

などの利用が推奨されていると...

毎度モヤモヤ感が半端ない…

今回はこのへんで。