【问题标题】:Python threaded timer running function with passed variable带有传递变量的Python线程定时器运行函数
【发布时间】:2015-04-10 15:52:33
【问题描述】:

我正在尝试每 x 秒(在我的情况下为 60 秒)运行一个函数 (f),如果一个活动数据库连接存在,它将关闭它,并在完成后再次打开它。

我正在使用 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(最近一次调用最后一次):文件“input.py”,第 49 行,在 socketIO.wait() #保持连接打开文件“build/bdist.linux-x86_64/egg/socketIO_client/init.py”,第175行, 在等待文件 “build/bdist.linux-x86_64/egg/socketIO_client/init.py”,第 194 行, 在 _process_events 文件中 “build/bdist.linux-x86_64/egg/socketIO_client/init.py”,第 202 行, 在 _process_packet 文件中 “build/bdist.linux-x86_64/egg/socketIO_client/init.py”,第 327 行, 在 _on_event 文件“input.py”中,第 36 行,在 on_message 中 cur.execute(("%s")%(query)) 文件“/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py”,第 155 行,在 执行 字符集 = db.character_set_name() _mysql_exceptions.InterfaceError: (0, '') 线程 Thread-1 中的异常:回溯(最近一次调用):文件 “/usr/lib/python2.7/threading.py”,第 810 行,在 __bootstrap_inner self.run() 文件“/usr/lib/python2.7/threading.py”,第 1082 行,运行中 self.function(*self.args, **self.kwargs) TypeError: * 后面的 f() 参数必须是序列,而不是连接

也许有一个更适合我需要的方法,但重要的是连接关闭,函数运行并且每隔一分钟左右再次打开连接。想过一个 cron 工作,但我宁愿让我的代码做所有事情。

【问题讨论】:

    标签: function python-2.7


    【解决方案1】:

    根据Timer object,它的第三个参数是args。这是一个列表,但您只传递了con
    您需要将问题行替换为:

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

    【讨论】:

      猜你喜欢
      • 2018-01-07
      • 2011-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多