我将如何在python中创建(异步/线程/任务)backgroundqueue?

时间:2018-03-28 10:49:50

标签: python python-3.x redis python-asyncio

对于C#应用程序,我使用了一个backgroundqueue,在那里我可以排队' action' in。我希望在Python中也这样做。

背景队列应该排队'一个'行动'它包含对函数的调用(带或不带变量),并且应该在主程序继续执行自己的功能时继续执行任务。

我已经尝试过使用rq,但这似乎不起作用。我很乐意听到一些建议!

编辑: 这是关于的代码:

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()

如果有意义的话,create_new_npy_files(filename)是静态类的静态方法。这是一个非常耗时的功能(1-2秒)

1 个答案:

答案 0 :(得分:3)

如果要执行的操作很短且无阻塞,您可以使用call_soon

loop = asyncio.get_event_loop()
loop.call_soon(action, args...)

如果操作可能需要更长时间或可能阻止,请使用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.

请注意,上述两个代码段都假定您已在程序中使用asyncio,具体取决于python-asyncio标记。这意味着您的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(...)