Python时间。睡觉()获取web内容的替代方法

2024-04-19 21:54:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python为我的Raspberry Pi编写一个天气显示程序,它使用天气网的api。现在,我已经设置它在每次主“while”循环后休眠5分钟。这是因为我不希望Pi不断地使用wifi获取相同的天气数据。问题是,如果我试图以任何方式关闭或更改程序,它将等待完成时间。睡觉()函数,然后继续。我想添加按钮来创建一个滚动菜单,但目前,程序将挂在那时间。睡觉()函数,然后继续。在保持程序响应性的同时,有没有其他方法可以用来延迟数据的获取?在


Tags: 数据方法函数程序api方式时间菜单
3条回答

你可以这样做:

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

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

顺便说一句:如果获取web内容需要更多的时间,那么就在线程中运行它。在

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

相关问题 更多 >