这是你的小程序,只需在 cron 中每隔一分钟运行一次
#!/usr/bin/env python
from random import randrange
import datetime
now = datetime.datetime.now()
#generate random temperature
temperature = randrange(50, 100)
#database structure
structure = "{'last_hour': [], 'last_3_hours': [], 'last_12_hours': [], " \
"'last_24_hours': [], 'last_7_days': []}"
#file for the database
database = 'temperature_database.txt' #use absolute path when running from cron
#check database file exists, if not write the database structure
try:
with open(database): pass
except IOError:
with open(database, 'w') as handler:
handler.write(structure)
#read the contents of the database
with open(database, 'r') as handler:
db_contents = eval(handler.read())
#first save every minute
db_contents['last_hour'].append(temperature)
if len(db_contents['last_hour']) > 60:
db_contents['last_hour'] = db_contents['last_hour'][-60:] #get the last 60 elements
if now.minute in [10, 0]: #every ten minutes
db_contents['last_3_hours'].append(temperature)
if len(db_contents['last_3_hours']) > 18:
db_contents['last_3_hours'] = db_contents['last_3_hours'][-18:]
db_contents['last_12_hours'].append(temperature)
if len(db_contents['last_12_hours']) > 72:
db_contents['last_12_hours'] = db_contents['last_12_hours'][-72:]
db_contents['last_24_hours'].append(temperature)
if len(db_contents['last_24_hours']) > 144:
db_contents['last_24_hours'] = db_contents['last_24_hours'][-144:]
if now.minute == 1: #every hour
db_contents['last_7_days'].append(temperature)
if len(db_contents['last_7_days']) > 168:
db_contents['last_7_days'] = db_contents['last_7_days'][-168:]
#save the contents to the database
with open(database, 'w') as handler:
handler.write(str(db_contents))
四分钟后,文件包含
{'last_hour': [62, 99, 83, 71], 'last_12_hours': [], 'last_24_hours': [], 'last_3_hours': [], 'last_7_days': []}