APScheduler线程设计模式

APScheduler Threading design pattern

我目前正在编写一个应用程序来使用 APScheduler (3.6.0) 和 python3.6

安排一些指标

5-6 天后 运行,调度程序停止,没有任何错误。所以我认为这可能是资源/并发问题。

我有不同的时间表,例如每 15 分钟、每 30 分钟、每小时等...

我的调度程序初始化如下,我现在只使用线程:

    executors = {
    'default': ThreadPoolExecutor(60),
    'processpool': ProcessPoolExecutor(5)
}

scheduler = BackgroundScheduler(timezone="Europe/Paris", executors=executors)

我的问题如下:当多个作业开始时,通过相同的代码部分,这可能是一个潜在的概念错误吗?那我需要加锁吗? 例如,他们使用相同的代码部分连接到数据库(相同的模块)并检索结果

def executedb(data):
    cursor = None
    con = None

    try:
        dsn = cx.makedsn(data[FORMAT_CFG_DB_HOST], data[FORMAT_CFG_DB_PORT],
                         service_name=data[FORMAT_CFG_DB_SERVICE_NAME])
        con = cx.connect(user=data[FORMAT_CFG_DB_USER], password=data[FORMAT_CFG_DB_PASSWORD], dsn=dsn)

        cursor = con.cursor()
        sql = data[FORMAT_METRIC_SQL]

        cursor = cursor.execute(sql)

        rows = rows_to_dict_list(cursor)


        if len(rows) > 1:
            raise Exception("")

    except Exception as exc:
        raise Exception('')
    finally:
        try:
            cursor.close()
            con.close()
        except Exception as exc:
            raise Exception('')

    return rows

这会导致线程并发吗?执行此操作的最佳设计模式是什么?

如果您的进程中有多个线程,那么当您连接到数据库时,您应该确保启用线程模式,如下所示:

con = cx.connect(user=data[FORMAT_CFG_DB_USER], password=data[FORMAT_CFG_DB_PASSWORD], dsn=dsn, threaded=True)

否则,您 运行 将面临破坏内存或导致其他问题的真正风险。也许这就是您问题的根源?