2015-02-10 93 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()