3058

Python スクリプトに時間遅延を設定する方法を知りたいです。

4

13 に答える 13

3277
import time
time.sleep(5)   # Delays for 5 seconds. You can also use a float value.

以下は、約 1 分に 1 回何かが実行される別の例です。

import time
while True:
    print("This prints once a minute.")
    time.sleep(60) # Delay for 1 minute (60 seconds).
于 2009-02-04T07:05:59.533 に答える
849

モジュールでsleep()関数をtime使用できます。1 秒未満の精度で float 引数を取ることができます。

from time import sleep
sleep(0.1) # Time in seconds
于 2008-09-15T16:34:29.780 に答える
55

眠そうな発電機でちょっとした楽しみ。

時間の遅れについて質問です。一定の時間にすることもできますが、場合によっては、前回から測定された遅延が必要になることがあります。考えられる解決策の 1 つを次に示します。

前回から測定された遅延 (定期的に起きている)

状況としては、何かをできるだけ定期的に実行したいが、コードの周りにあるすべてのものlast_timeに煩わされたくない場合があります。next_time

ブザー発生器

次のコード ( sleepy.py ) は、buzzergenジェネレーターを定義します。

import time
from itertools import count

def buzzergen(period):
    nexttime = time.time() + period
    for i in count():
        now = time.time()
        tosleep = nexttime - now
        if tosleep > 0:
            time.sleep(tosleep)
            nexttime += period
        else:
            nexttime = now + period
        yield i, nexttime

通常のブザーゲンを呼び出す

from sleepy import buzzergen
import time
buzzer = buzzergen(3) # Planning to wake up each 3 seconds
print time.time()
buzzer.next()
print time.time()
time.sleep(2)
buzzer.next()
print time.time()
time.sleep(5) # Sleeping a bit longer than usually
buzzer.next()
print time.time()
buzzer.next()
print time.time()

実行すると、次のようになります。

1400102636.46
1400102639.46
1400102642.46
1400102647.47
1400102650.47

ループで直接使用することもできます。

import random
for ring in buzzergen(3):
    print "now", time.time()
    print "ring", ring
    time.sleep(random.choice([0, 2, 4, 6]))

実行すると、次のように表示されます。

now 1400102751.46
ring (0, 1400102754.461676)
now 1400102754.46
ring (1, 1400102757.461676)
now 1400102757.46
ring (2, 1400102760.461676)
now 1400102760.46
ring (3, 1400102763.461676)
now 1400102766.47
ring (4, 1400102769.47115)
now 1400102769.47
ring (5, 1400102772.47115)
now 1400102772.47
ring (6, 1400102775.47115)
now 1400102775.47
ring (7, 1400102778.47115)

ご覧のとおり、このブザーは硬すぎず、寝坊して通常のスケジュールから外れても、定期的な眠気の間隔に追いつくことができます。

于 2014-05-14T21:30:35.883 に答える