【发布时间】:2021-11-14 23:43:00
【问题描述】:
这就是我想要做的:我想在 24 小时内每小时运行以下函数。此函数从 api 收集数据,将值附加到字典并将其保存为 json 文件以供以后使用。我正在运行的代码工作正常,但它并不优雅,因为我必须使用 KeyboardInterrupt 来停止它。我希望脚本在 24 小时后停止运行并每小时打印一次:print('data successfully collected at ' + time.ctime()
def weather_collect():
url = 'http://api.openweathermap.org/data/2.5/weather?lat={}&lon={}&appid={}&units=metric'
response = requests.get(url.format(lat,lon, api_key))
r = response.json()
data['temperature'].append(r['main']['temp'])
data['humidity'].append(r['main']['humidity'])
data['pressure'].append(r['main']['pressure'])
data['visibility'].append(r['visibility'])
data['wind_speed'].append(r['wind']['speed'])
data['time'].append(time.ctime())
with open('data.json', 'w') as f:
f.write(json.dumps(data))
return data
schedule.every(1).hour.do(weather_collect)
while 1:
schedule.run_pending()
time.sleep(1)
【问题讨论】:
标签: python file scheduled-tasks