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 5 years have passed since last update.

python3で定期的に処理を実行

Last updated at Posted at 2018-12-13
  • Windowsのpythonで定期実行したかった。 
  • 誤差が離れていくのがいやだった。

(将来の区切りがいい時間)-(今の時間)を待つ事にしてみた。

import time
interval = 0.1
for i in range (0,20,1):
    time.sleep(round((time.time() + interval),1) - time.time() )
    print(time.time())    

結果

1544677358.100609
1544677358.2011507
1544677358.3008385
1544677358.401767
1544677358.500938
1544677358.6018412
1544677358.7008717
1544677358.8017764
1544677358.9017441
1544677359.0014997
1544677359.1006112
1544677359.2011628
1544677359.3005452
1544677359.4007142
1544677359.5016642
1544677359.6016362
1544677359.7016027
1544677359.801553
1544677359.9015212
1544677360.0014884

#追記(2019-02-17)
何か処理時間を挟むとちょっとずれて行ってしまうことがある問題を修正出来るバージョン
予め次回起動時間を計算しておき何か処理が終わってからSleep時間を決定する様にした。

import time
interval = 0.1 #「何か処理」が必ず終わる間隔を指定する必要がある。
for i in range (0,20,1):
    next_time =  round((time.time() + interval),1)
    #「何か処理」をかく。
    time.sleep( next_time - time.time() )
    print(time.time())    

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
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?