如何安排Python脚本终止?

2024-10-01 05:01:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在使用python在数据库中的表上循环执行繁重的处理任务。为了对其他用户友好,我希望这种处理只能在夜间进行。当早起的人开始使用数据库时,我希望能够编程提前终止这个脚本。你知道吗

我知道interrupting cow,所以我可以有这样的东西:

from interruptingcow import timeout

from dbsettings import dbsetting

con = connect(database=dbset['database'],
              host=dbset['host'],
              user=dbset['user'],
              password=dbset['password'])
cursor = con.cursor()

YEARS = {"2014":range(1, 13),
         "2015":range(1, 13)}

def update_table(yyyymm, con, cursor)
     table = 'public.tablename'+yyyymm
     cursor.execute('Do something on {table}'.format(table))
     con.commit()

try:
    with timeout(57600, exception=RuntimeError):
        for year in YEARS:
            for month in years[year]:
                yyyymm = get_yyyymm(year, month)
                update_table(yyyymm, con, cursor)
except RuntimeError:
    print "It's morning, killing database processing"

但这是最佳实践吗?有更好的办法吗?你知道吗


Tags: fromimport数据库hosttabletimeoutpasswordcon