繁体   English   中英

如何在指定的时间段内调用该函数?

[英]how do i call the function in specified period of time?

我正在尝试构建一个学习器,该学习器将调用该函数并将权重存储到数据库中,现在的问题是,学习至少需要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的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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM