【问题标题】:how do i call the function in specified period of time?如何在指定的时间段内调用该函数?
【发布时间】:2018-10-21 18:02:59
【问题描述】:

我正在尝试构建一个学习器,它将调用该函数并将权重存储到数据库中,现在的问题是,学习至少需要 30 到 60 秒,所以如果我想存储我需要等待我决定用线程定时器调用函数,它会在指定的时间段后调用函数,

代码示例:

def learn(myConnection):
    '''
    Derive all the names,images where state = 1
    Learn and Store
    Delete all the column where state is 1
    '''
    id = 0

    with myConnection:

        cur = myConnection.cursor()
        cur.execute("Select name, image FROM images WHERE state = 1")
        rows = cur.fetchall()

        for row in rows:
            print "%s, %s" % (row[0], row[1])

            name ='images/Output%d.jpg' % (id,)
            names = row[0]

            with open(name, "wb") as output_file:
                output_file.write(row[1])


            unknown_image = face_recognition.load_image_file(name)
            unknown_encoding = face_recognition.face_encodings(unknown_image)[0]

            # here i give a timer and call the function 
            threading=Timer(60,  storeIntoSQL(names,unknown_encoding) )
            threading.start()

            id += 1

对此不起作用的事情是,它就像我没有指定计时器一样工作它没有等待 60 秒它只是正常工作,就好像我在没有计时器的情况下调用函数一样,关于我如何做的任何想法使这项工作或我可以使用什么替代品? ... PS 我已经使用了 time.sleep 它只是停止了我需要项目在训练时运行的主线程

正在调用的函数示例:

def storeIntoSQL(name,unknown_face_encoding):
    print 'i am printing'
    # connect to the database
    con = lite.connect('users2.db')
    # store new person into the database rmena
    with con:
        cur = con.cursor()
        # get the new id
        cur.execute("SELECT DISTINCT id FROM Users ")
        rows = cur.fetchall()
        newId = len(rows)+1            
        # store into the Database
        query = "INSERT INTO Users VALUES (?,?,?)"
        cur.executemany(query, [(newId,name,r,) for r in unknown_face_encoding])
    con

我还被告知 MUTEX 同步可能会有所帮助,只有当另一个线程完成它的工作时我才能使一个线程工作,但我不知道如何实现它并且愿意接受任何建议

【问题讨论】:

    标签: python multithreading deep-learning mutex


    【解决方案1】:

    我建议使用 python 的threading 库并在函数内部或包装函数中的某处实现time.sleep(60)。例如

    import time
    import threading
    
    def delayed_func(name,unknown_face_encoding):
        time.sleep(60)
        storeIntoSQL(name,unknown_face_encoding)
    
    timer_thread = threading.Thread(target=delayed_func, args=(name,unknown_face_encoding))
    timer_thread.start()
    

    【讨论】:

    • 它可以工作,谢谢它并没有停止整个程序,但它仍然无法按照我想要的方式工作,它首先将空值存储在列中,然后将正确的值存储在以下列中试着想办法阻止它,但谢谢。
    • 我还想问一下,time.sleep() 只为我调用它的正确线程停止工作?因为我之前调用过它,它停止了所有线程的运行
    • 在这种情况下是的,因为 time.sleep 在特定线程中被调用,它只会延迟该线程。关于空值,我认为它可能与其余代码有关,而不是与计时器有关
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 2019-07-14
    • 1970-01-01
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多