python+;mysql使代码每分钟工作一次

python+;mysql使代码每分钟工作一次,python,mysql,Python,Mysql,你好 我很难让它每分钟工作一次 我希望它在代码中工作,而不是像crontab一样 还有一个代码将数据插入mysqldb,我不希望数据无限增长我想让它工作自动删除超过1000个或超过一周的数据如果你的唯一目标是每n分钟运行一次代码,而你不想使用(,你完全应该这么做)这是一个简单的解决方案,但有一些缺点: database. dbConn = MySQLdb.connect("localhost","database_username","password","database_name") or

你好 我很难让它每分钟工作一次 我希望它在代码中工作,而不是像crontab一样
还有一个代码将数据插入mysqldb,我不希望数据无限增长我想让它工作自动删除超过1000个或超过一周的数据如果你的唯一目标是每
n
分钟运行一次代码,而你不想使用(,你完全应该这么做)这是一个简单的解决方案,但有一些缺点:

database.
dbConn = MySQLdb.connect("localhost","database_username","password","database_name") or die ("could not connect to database")

cursor = dbConn.cursor()

device = '/dev/tty.usbmodem1411' #this will have to be changed to the serial port you are using
try:
  print "Trying...",device 
  arduino = serial.Serial(device, 9600) 
except: 
  print "Failed to connect on",device    

try: 
  data = arduino.readline()  
  pieces = data.split("\t")  

try:
    cursor.execute("INSERT INTO weatherData (humidity,tempC) VALUES (%s,%s)", (pieces[0],pieces[1]))
    dbConn.commit() #commit the insert
    cursor.close()  #close the cursor
except MySQLdb.IntegrityError:
    print "failed to insert data"
finally:
    cursor.close()  #close just incase it failed
except:
    print "Failed to get data from Arduino!"
如果在后台运行,则需要使用操作系统提供的工具终止进程。如果重新启动设备,则需要手动启动脚本(或以某种方式自动启动)


这就解决了问题,但是你应该真正地使用Cron来处理类似的事情。

请更正代码的标识。你到底想干什么?您想每
n
分钟运行一次此脚本吗?我想每n分钟运行一次此代码,或者只运行插入的代码,我想让它每n分钟自动将数据输入数据库
from time import sleep

sleep_for_n_minutes = 1

while True:
    # Your code goes here

    # Sleep for n minutes (sleep takes seconds -> multiply by 60)
    sleep(sleep_for_n_minutes * 60)