2016-12-16 36 views
0

我正在爲使用weather.com的api提取數據的python編寫我的Raspberry Pi的天氣顯示程序。就目前來看,我已經在每個主'while'循環後將它設置爲休眠5分鐘。這是因爲我不希望Pi經常使用WiFi來獲取相同的天氣數據。這個問題是,如果我嘗試以任何方式關閉或更改程序,它會在繼續之前等待完成time.sleep()函數。我想添加按鈕來創建一個滾動菜單,但目前,程序將在繼續之前掛在time.sleep()函數中。有沒有其他方法可以用來延遲數據的提取,同時保持程序響應?python time.sleep()提取網頁內容的替代方案

+0

你不清楚你在問什麼,你可能想寫一個[MCVE]來演示你遇到的問題。 – pvg

+0

你可以減少睡眠時間到1秒,並把它放在一個循環中:'for my in xrange(300):time.sleep(1)'。 –

+0

'pygame'有'pygame.time',你可以使用'pygame.time'來檢查時間並在'while True'循環中執行命令。 – furas

回答

1

你可以做這樣的事情:

import time, threading 
def fetch_data(): 
    # Add code here to fetch data from API. 
    threading.Timer(10, fetch_data).start() 

fetch_data() 

則fetch_data方法將一個線程中執行,所以你不會有太大的問題。調用該方法之前還有一段延遲。所以你不會轟炸API。

示例源:Executing periodic actions in Python

0

與Python的time模塊

import time 

timer = time.clock() 
interval = 300 # Time in seconds, so 5 mins is 300s 

# Loop 

while True: 
    if timer > interval: 
     interval += 300 # Adds 5 mins 
     execute_API_fetch() 

    timer = time.clock() 
+0

它不起作用 - 它只等待5分鐘一次 - 不定期 – furas

0

Pygame的具有pygame.time.get_ticks(),你可以用它來檢查時間,並用它在主循環執行函數創建一個定時器。

import pygame 

# - init - 

pygame.init() 

screen = pygame.display.set_mode((800, 600)) 

# - objects - 

curr_time = pygame.time.get_ticks() 

# first time check at once 
check_time = curr_time 

# - mainloop - 

clock = pygame.time.Clock() 

running = True 

while running: 

    # - events - 

    for event in pygame.event.get(): 
     if event.type == pygame.QUIT: 
      running = False 
     elif event.type == pygame.KEYDOWN: 
      if event.key == pygame.K_ESCAPE: 
      running = False 

    # - updates - 

    curr_time = pygame.time.get_ticks() 

    if curr_time >= check_time: 
     print('time to check weather') 

     # TODO: run function or thread to check weather 

     # check again after 2000ms (2s) 
     check_time = curr_time + 2000 

    # - draws - 
     # empty 

    # - FPS - 

    clock.tick(30) 

# - end - 

pygame.quit() 

順便說一句:如果抓取web內容需要更多時間,然後在線程中運行它。