2016-05-17 4 views
2

スクリプトが開始されているので、さまざまなタイミング(リストを作成する)で「hello world」というテキストをスケジュールします。それをする最善の方法は何でしょうか?スクリプトがPythonで起動した後の特定のタイミングで印刷コマンドをスケジュールする

これはおそらく間違っているが、私はこれまで持っているもの:

import time 
times = [1.76493425, 3.10174059, 4.49576803, 10.99379224, 18.84178369] #at these times since onset of script, a text "hello world" should be printed 

start = time.time() 

def main(): 
    for cuetime in times: 
     print ('hello world', ' - timing: ', cuetime, ' - now: ', time.time()- start) 
    yield viztask.waitTime(cuetime) 

main() 

これは私に与える:

('hello world', ' - timing: ', 1.76493425, ' - now: ', 0.0) 
('hello world', ' - timing: ', 3.10174059, ' - now: ', 1.7699999809265137) 
('hello world', ' - timing: ', 4.49576803, ' - now: ', 3.5379998683929443) 
('hello world', ' - timing: ', 10.99379224, ' - now: ', 5.305999994277954) 
('hello world', ' - timing: ', 18.84178369, ' - now: ', 7.075000047683716) 

しかし、私は実際に必要なのと同じになるようにタイミング要素/アイテムですタイミングリストの要素は、スクリプトの開始点に対する相対的なテキスト「hello world」の印刷タイミングであるため、「今」の時間になります。

答えて

0

scheduleとは何ですか?前にそれで働いていないが、あなたは非常に簡単にあなたの目標を達成することができます

import schedule 
import time 
from functools import partial 
# your specified list of times 
times = [1.76493425, 3.10174059, 4.49576803, 10.99379224, 18.84178369] 
# define a job you want to do 
def job(t, start): 
    print ('hello world', ' - timing: ', t, ' - now: ', time.time()- start) 
    # pop the job right away from schedule.jobs, so it runs only once 
    return schedule.CancelJob 
# get the starting time 
start = time.time() 
# for each time add what to do 
for t in times: 
    # using partial so i can pass arguments to job 
    schedule.every(t).seconds.do(partial(job, t, start)) 
# and run it inside a lop 
while True: 
    schedule.run_pending() 
    # schedule.jobs is just a list of jobs 
    if not schedule.jobs: 
     break 

プリントアウト:

hello world - timing: 1.76493425 - now: 1.7650279998779297 
hello world - timing: 3.10174059 - now: 3.101846933364868 
hello world - timing: 4.49576803 - now: 4.495898962020874 
hello world - timing: 10.99379224 - now: 10.993950605392456 
hello world - timing: 18.84178369 - now: 18.84195566177368 
+1

感謝を移動するための方法だった、これは、優れた、特にそれを透明にするコメント。 – Spica

+0

私はそれが助けてうれしいです。それを改善する余地があります。おそらく毎回 'start'を渡します。何らかの理由で私はデコレータとコンテキストマネージャを考えています。しかし、もし仕事がより複雑であれば、それらは興味深いだろう。 – quapka

1

詳しくはschedライブラリをご覧ください。 100%正確ではないコードサンプルですが、ミリ秒の精度を必要としない場合はこのトリックを行う必要があります。

import time 
import sched 

def print_time(cuetime): 
    global start 
    print ('hello world', ' - timing: ', cuetime, ' - now: ', time.time()- start) 

start = time.time() 
times = [1.76493425, 3.10174059, 4.49576803, 10.99379224, 18.84178369] 

if __name__ == "__main__": 
    s = sched.scheduler(time.time, time.sleep) 
    for cuetime in times: 
     s.enter(cuetime, 1, print_time, (cuetime,)) 
    s.run() 
+0

おかげリュックは、スケジューラはdefinetely quapka – Spica

関連する問題