[英]How would I go and create an (async/threaded/task) backgroundqueue in python?
For a C# application I have used a backgroundqueue where I could enqueue 'actions' in. I wish to do the same in Python. 对于C#应用程序,我使用了一个backgroundqueue,我可以在其中排队'actions'。我希望在Python中也这样做。
The backgroundqueue should 'enqueue' an 'action' which contains a call to a function (with or without variables) and should keep going through the tasks while the main program keeps doing its own function. backgroundqueue应该“排队”包含对函数的调用(带或不带变量)的'action',并且应该在主程序继续执行自己的函数时继续执行任务。
I already tried with rq, but that seemed not to work. 我已经尝试过rq,但这似乎不起作用。 I would love to hear some suggestions! 我很乐意听到一些建议!
Edit: The code this is about: 编辑:这是关于的代码:
class DatabaseHandler:
def __init__(self):
try:
self.cnx = mysql.connector.connect(user='root', password='', host='127.0.0.1', database='mydb')
self.cnx.autocommit = True
self.loop = asyncio.get_event_loop()
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
self.get_new_entries(30.0)
async def get_new_entries(self, delay):
start_time = t.time()
while True:
current_time = datetime.datetime.now() - datetime.timedelta(seconds=delay)
current_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
data = current_time
print(current_time)
await self.select_latest_entries(data)
print("###################")
t.sleep(delay - ((t.time() - start_time) % delay))
async def select_latest_entries(self, input_data):
query = """SELECT FILE_NAME FROM `added_files` WHERE CREATION_TIME > %s"""
cursor = self.cnx.cursor()
await cursor.execute(query, (input_data,))
async for file_name in cursor.fetchall():
file_name_string = ''.join(file_name)
self.loop.call_soon(None, self.handle_new_file_names, file_name_string)
cursor.close()
def handle_new_file_names(self, filename):
# self.loop.run_in_executor(None, NF.create_new_npy_files, filename)
# self.loop.run_in_executor(None, self.update_entry, filename)
create_new_npy_files(filename)
self.update_entry(filename)
def update_entry(self, filename):
print(filename)
query = """UPDATE `added_files` SET NPY_CREATED_AT=NOW(), DELETED=1 WHERE FILE_NAME=%s"""
update_cursor = self.cnx.cursor()
self.cnx.commit()
update_cursor.execute(query, (filename,))
update_cursor.close()
The create_new_npy_files(filename)
is a static method from a static class if that makes sense. 如果有意义, create_new_npy_files(filename)
是静态类的静态方法。 It is a pretty time consuming function (1-2 sec) 这是一个非常耗时的功能(1-2秒)
If the action to execute is short and non-blocking, you can use call_soon
: 如果要执行的操作很短且无阻塞,则可以使用call_soon
:
loop = asyncio.get_event_loop()
loop.call_soon(action, args...)
If the action can take longer or can block, use run_in_executor
to submit them to a thread pool: 如果操作可能需要更长时间或可以阻止,请使用run_in_executor
将它们提交到线程池:
loop = asyncio.get_event_loop()
future = loop.run_in_executor(None, action, args...)
# you can await the future, access its result once ready, etc.
Note that both above snippets assume that you already use asyncio
in your program, based on the python-asyncio
tag. 请注意,上述两个片段都假定您已在程序中使用asyncio
,基于python-asyncio
标记。 This means that your select_statement
would look like this: 这意味着您的select_statement
将如下所示:
async def select_statement():
loop = asyncio.get_event_loop()
while True:
# requires an async-aware db module
await cursor.execute(query, (input_data,))
async for file_name in cursor.fetchall():
loop.call_soon(self.handle_new_file_names, file_name_string))
# or loop.run_in_executor(...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.