簡體   English   中英

在python中,如何在給定的系統時間啟動程序?

[英]In python, how can I begin a program at a given system time?

在python中,我一直在使用sleep每小時,每分鍾或每天執行一次循環代碼。 問題是腳本運行大約需要1-3秒。 我如何確保下一分鍾到來時腳本開始執行,例如,我啟動了腳本並且當前分鍾還剩20秒。

使用時間,我得到這些結果,請注意,我每秒都會失去精度:

Waiting for next half min.
2013-09-14 15:46:53.850068
307
Waiting for next half min.
2013-09-14 15:47:24.158642
307
Waiting for next half min.
2013-09-14 15:47:54.717070
302
Waiting for next half min.
2013-09-14 15:48:25.296409
325
Waiting for next half min.
2013-09-14 15:48:55.506098

我認為您的計時不精確是由於無法預測的python解釋器啟動時間。

如果需要確保實際代碼在正確的時間開始執行,可以執行以下操作:

  • 使您的腳本比您需要的運行時間早一點
  • 在腳本中:

     import time import datetime schedule_time = ... # parse sys.argv or whatevs # this will wait exactly as much time as it is left before the schedule time.sleep((schedule_time - datetime.datetime.now()).total_seconds()) # ... your code 

每次代碼運行后,您需要計算適當的睡眠時間。 以下代碼執行此操作,並且在工作任務花費的時間超過延遲間隔的情況下,還嘗試進行跟蹤。

import time

# Get the start time, also the time of the next (first) iteration
lTimeNext = time.time()

# Set up the delay time
lDelay = 30

# Loop, doing work
while True:

  # Do Work
  print "Working!"

  # Work out when to do the next work item
  lTimeNext += lDelay

  # Sleep until the next work is required
  lSleepTime = lTimeNext - time.time()
  if lSleepTime > 0:
    time.sleep(lSleepTime)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM