LoginSignup
32
18

More than 5 years have passed since last update.

timeout-decoratorを利用して自作関数にタイムアウトを設定する

Posted at

やりたいこと

自作関数でタイムアウトを設定して、時間内に終了しなければ別の処理を実行させたい
ちょっと調べたらtimeout-decoratorに出会って使い勝手がよかったので、紹介したいと思います

前提

  • python 3.5.2
  • time_decorator 0.4.0

インストール

$ pip install timeout-decorator

使い方

1. 固定値で関数にタイムアウトを実装

@timeout(5)というように値を設定すればよいだけ

#!/usr/bin/env python
#-*- coding:utf-8 -*-

"""
Time out test 1
"""

import time

from timeout_decorator import timeout, TimeoutError

@timeout(5)
def func():
    """func"""
    for i in range(0, 10):
        print("i :%d" % i)
        time.sleep(i)

def callback():
    """callback"""
    print("callback")

def main():
    """
    main
    """

    try:
        func()
    except TimeoutError:
        callback()

if __name__ == "__main__":
    main()

2. タイムアウト値を変数で受け取る場合

関数内関数を利用して、タイムアウト値を引数で変更できるようにしています。

#!/usr/bin/env python

"""
Timeout test
"""

import time

from timeout_decorator import timeout, TimeoutError


def run_func_with_timeout(timeout_sec, func, *args, **kargs):
    """
    run func with timeout
    """
    print("timeout sec: %d" % timeout_sec)

    @timeout(timeout_sec)
    def target(*args, **kargs):
        """target"""
        func(*args, **kargs)
    target(*args, **kargs)

def func_test(inputs):
    """
    test
    """

    print("inputs = %d" % inputs)

    for i in range(0, 100):
        print("i: %d" % i)
        time.sleep(1)

def callback():
    """callback"""
    print("callback")

def main():
    """
    main
    """

    try:
        run_func_with_timeout(func=func_test,
                              timeout_sec=5,
                              x=5)
    except TimeoutError:
        callback()

if __name__ == "__main__":
    main()
32
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
32
18