2015-02-10 49 views
0

我试图运行一个函数(f)每x秒(在我的情况下60),它将关闭活动的数据库连接,如果存在,并在完成后再次打开它。Python线程计时器运行函数与传递变量

我正在使用threading.timer,虽然我无法将连接传递到函数中,并且在某些情况下该函数重复运行而没有其他运行。

该函数需要返回连接到全局变量完成后,我发现很难将连接传递给该函数,并从函数内全局分配返回值,这是我相信threading.timer的工作原理:

enter code from socketIO_client import SocketIO 
import logging 
import json 
import MySQLdb as mdb 
import os 
import threading 
con = mdb.connect('localhost','username','password','databaseName') 
cur = con.cursor() 

def f(con): 
    if 'con' in globals(): 
     con.close() 
     print ("Connection closed") 
    os.system('php -f /home/ubuntu/grab.php') 
    con = mdb.connect('localhost','username','password','databaseName') 
    cur = con.cursor() 
    print ("DB Connection opened") 
    con = mdb.connect('localhost','username','password','databaseName') 
    cur = con.cursor() 
    threading.Timer(60,f,con).start(); ######PROBLEM LINE 
    return con 
def on_connect(): 
    print "Connecting to database" 
    areas = ['EH','BE'] 
    socketIO.emit('subscribe_areas', areas) 
def on_message(answer): 
    print("\nNew message received") 

    array = (json.loads(answer)) 
    print (array) 
    runningIdentity = array["value"] 
    berthID = array["to"] 
    area = array["area"] 
    if berthID: 
     query = ("SELECT crs FROM signalBerth WHERE signalBerth=\'%s\';"%(berthID)) 
     cur.execute(("%s")%(query)) 
     reply = cur.fetchall() 
     for row in reply: 
      crs= row[0] 
      query = "UPDATE service SET lastSeen = \'%s\' WHERE runningIdentity=\'%s"%(crs,runningIdentity)+"\';" #berthID == crs, need to alter 
      print (("%s")%(query)) 
      cur.execute(("%s")%(query)) 
      con.commit() 
      print("affected rows = {}".format(cur.rowcount)) 
socketIO = SocketIO('http://www.realtimetrains.co.uk', 41280) #opens connection 
socketIO.on('connect', on_connect)        #sends subscription 
socketIO.on('message', on_message)        #reads data, creates mysql and executes it 
con = f(con)  ######FIRST CALL TO FUNCTION 
socketIO.wait()             #Keeps connection openhere 

错误:

Traceback (most recent call last): File "input.py", line 49, in socketIO.wait() #Keeps connection open File "build/bdist.linux-x86_64/egg/socketIO_client/init.py", line 175, in wait File "build/bdist.linux-x86_64/egg/socketIO_client/init.py", line 194, in _process_events File "build/bdist.linux-x86_64/egg/socketIO_client/init.py", line 202, in _process_packet File "build/bdist.linux-x86_64/egg/socketIO_client/init.py", line 327, in _on_event File "input.py", line 36, in on_message cur.execute(("%s")%(query)) File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 155, in execute charset = db.character_set_name() _mysql_exceptions.InterfaceError: (0, '') Exception in thread Thread-1: Traceback (most recent call last): File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner self.run() File "/usr/lib/python2.7/threading.py", line 1082, in run self.function(*self.args, **self.kwargs) TypeError: f() argument after * must be a sequence, not Connection

或许有我需要一个更合适的方法,但是它的连接被关闭了重要的一点,功能运行和连接再次打开每分钟左右。思考一个cron工作,但我宁愿让我的代码做所有事情。

回答

1

根据Timer object,其第三个参数是args。这是一个列表,但你只能通过con
您需要将您的问题行替换为:

threading.Timer(60, f, (con,)).start()