【问题标题】:python+mysql making the code work every minutespython+mysql 使代码每分钟工作一次
【发布时间】:2017-03-02 00:16:37
【问题描述】:
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!"

你好 我很难让它每隔几分钟工作一次 我希望它在不像 crontab 的代码中工作 还有一个代码将数据插入到 mysqldb 中,我不希望数据无限增长,我想让它自动删除超过一千的数据或超过一周的数据

【问题讨论】:

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

标签: python mysql


【解决方案1】:

如果您的唯一目标是每 n 分钟运行一次该代码,并且您不想使用 Cron您完全应该这样做),这是一个简单的解决方案,但有一些缺点:

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)

如果您在后台运行此程序,您需要使用操作系统提供的工具终止该进程。如果您重新启动设备,您将需要手动启动脚本(或以某种方式自动化)。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 1970-01-01
    • 2016-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多