用于获取Web内容的Python time.sleep()替代方法

时间:2016-12-16 05:53:18

标签: python pygame

我正在为python中的Raspberry Pi编写天气显示程序,使用weather.com的api获取数据。就目前而言,我已将其设置为在每个主要'while'循环后休眠5分钟。这是因为我不希望Pi不断使用wifi来获取相同的天气数据。这样做的问题是,如果我试图以任何方式关闭或改变程序,它会等待在继续之前完成time.sleep()函数。我想添加按钮来创建滚动菜单但是目前,程序将在继续之前挂起time.sleep()函数。有没有其他方法可以用来延迟数据的提取,同时保持程序的响应能力?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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()

答案 2 :(得分:0)

Pygame有pygame.time.get_ticks(),你可以用它来检查时间并用它来执行mainloop中的函数。

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()

顺便说一句:如果获取网页内容需要更多时间,请在线程中运行。