【问题标题】:Python time.sleep() alternatives for fetching web content用于获取 Web 内容的 Python time.sleep() 替代方法
【发布时间】:2017-05-01 21:01:18
【问题描述】:

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

【问题讨论】:

  • 不太清楚你在问什么,你可能想写一个minimal reproducible example 来说明你遇到的问题。
  • 您可以将睡眠时间减少到 1 秒并将其放入循环中:'for i in xrange(300): time.sleep(1)`。
  • pygamepygame.time,您可以使用它来检查时间并在while True 循环中执行命令。

标签: python pygame


【解决方案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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 它不起作用 - 它只等待 5 分钟 - 不是周期性的
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-26
      • 1970-01-01
      • 2018-08-27
      • 1970-01-01
      • 2021-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多