0

主な機能として while ループがあります。その中で、いくつかの IF ステートメントをチェックし、それに応じて関数を呼び出します。過去2分以内にすでに実行されている場合、呼び出したくない特定の関数。その間に他のIFテストを実行したいので、関数にWAIT()ステートメントを入れたくありません。

myFunction() を一時停止しようとする前のコードは次のようなものです

while not(exit condition):
    if(test):
        otherFunction()
    if(test):
        otherFunction()
    if(test):
        myFunction()

myFunction() を最大でも 2 分に 1 回だけ実行したい。その中に wait(120) を入れることもできますが、そうすると、その間に otherFunction() が呼び出されなくなります。

私は試した

import time

set = 0
while not(exit condition):
    if(test):
        otherFunction()
    if(test):
        otherFunction()
    if(test):
        now = time.clock()
        diff = 0
        if not(set):
            then = 0
            set = 1
        else:
            diff = now - then
            if (diff > 120):
            myFunction()
            then = now

成功せずに。それが正しいアプローチであるかどうか、そしてそうである場合、このコードが正しいかどうかはわかりません。初めてPython(実際にはSikuli)で作業しましたが、実行を追跡して実行方法を確認できないようです。

4

2 に答える 2

2

基本的には正しい軌道に乗っていると思いますが、実装方法は次のとおりです。

import time

MIN_TIME_DELTA = 120

last_call = time.clock() - (MIN_TIME_DELTA+1)  # init to longer than delta ago
while not exit_condition:
    if test:
        otherFunction()
    if test:
        anotherFunction()
    if test and ((time.clock()-last_call) > MIN_TIME_DELTA):
        last_call = time.clock()
        myFunction()

編集

わずかに最適化されたバージョンを次に示します。

next_call = time.clock() - 1  # init to a little before now
while not exit_condition:
    if test:
        otherFunction()
    if test:
        anotherFunction()
    if test and (time.clock() > next_call):
        next_call = time.clock() + MIN_TIME_DELTA
        myFunction()
于 2011-05-03T09:53:13.663 に答える
0

常に「今」を現在の時刻に設定します。else ブランチでは、常に "then" を now に設定します。したがって、diff は常に、if 句の最後の 2 つの実行の間に経過した時間です。「set」の値はコード内でのみ変更され、「0」に戻ることはありません。

代わりに次のようなことを行うこともできます (警告: テストされていないコード):

import time

set = 0
last_call_time = time.clock()

while not(exit condition):
    if(test):
        otherFunction()
    if(test):
        otherFunction()
    if(test):
        now = time.clock()
        diff = now - last_call_time
        if (diff > 120)
            myFunction()
            last_call_time = now
于 2011-05-03T08:35:43.790 に答える