微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

APScheduler线程设计模式

如何解决APScheduler线程设计模式

我目前正在编写一个应用程序,以使用APScheduler(3.6.0)和python3.6计划一些指标

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

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

我的Scheduler初始化如下,我现在仅使用线程:

    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)

如果不这样做,您将面临内存损坏或引起其他问题的真正风险。也许这就是问题的根源?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。