Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Pythonで一定時間(秒)以上処理をsleepさせる

Last updated at Posted at 2020-07-15

Pythonで一定時間以上処理を止めたい時の実装。

外部APIをfor文の中で何度も呼ぶときなどに、一定間隔を空けたいことがある。
でも必ず一定時間のsleepを入れてたらちょっと非効率。処理時間が一定間隔に満たなければsleepを入れたい。

例)Twitter APIへのリクエストの間隔を2秒以上空けたい。

import time
from datetime import datetime


def hoge():
    start = datetime.now()

    # ここでAPIリクエストやそれに付随する処理
    hoge()

    exec_time = (datetime.now() - start).microseconds

    # 処理に2秒以上かかってなければ最短2秒になるようにsleepする
    sleep_sec = float(2000 - exec_time) / 1000
    if sleep_sec > 0:
        time.sleep(sleep_sec)

もっといい書き方もありそう。

2
1
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

Qiita Conference 2025 will be held!: 4/23(wed) - 4/25(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

ymrl、Masanobu Naruse, Takeshi Kano, Junichi Ito, uhyo, Hiroshi Tokumaru, MinoDriven, Minorun, Hiroyuki Sakuraba, tenntenn, drken, konifar

View event details
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?