我有一个执行SELECTsql查询的函数(使用postgresql)。现在,我想将这个查询的执行时间插入到我的数据库中的某个表中,但是,我想并行地执行它,这样即使我的INSERT查询仍然在运行,我也能够继续我的程序并调用其他函数。
我尝试使用multiprocessing.process,但是,我的函数正在等待进程结束,实际上我失去了我想要的并行性的效果。
我的代码在一个坚果壳:
def select_func():
with connection.cursor() as cursor:
query = "SELECT * FROM myTable WHERE \"UserName\" = 'Alice'"
start = time.time()
cursor.execute(query)
end = time.time()
process = Process(target = insert_func, args = (query, (end-start)))
process.start()
process.join()
return cursor.fetchall()
def insert_func(query, time):
with connection.cursor() as cursor:
query = "INSERT INTO infoTable (\"query\", \"exec_time\")
VALUES (\"" + query + "\", \"" + time + "\")"
cursor.execute(query)
connection.commit()
现在的问题是这个操作不是真正异步的,因为select_func一直在等待insert_function的执行,我希望这些函数的执行不会被依赖,并且select函数可以在insert_function还在运行时结束,这样我就可以继续并调用脚本中的其他函数。
谢谢!
1条答案
按热度按时间jtw3ybtb1#
你的代码片段有很多问题,但是让我们试着至少给予一个要实现的结构。
考虑一个替代方案: