python - 每天在Python中的指定时间后执行常规任务

标签 python multithreading python-2.7 parsing time

我需要运行一些代码来存储我每天 23:30 后收集的值列表。为此,我使用了该代码:

 def sayac_yaz():

    threading.Timer(3600, sayac_yaz).start()

    save_time = datetime.datetime.now()
    if (save_time.hour<23):
        return 

    print "Sayaclari kaydediyor"

    if mem.sayac_okuma_flag==0:
        save_dict=mem.readings_from_counters

    # Connecting to the database file
    conn2 = sqlite3.connect('tenantdata.sqlite')
    c2 = conn2.cursor()

    for idx in save_dict:
        sayac_value=save_dict[idx]
        actual_counter_id=idx
        if isinstance(sayac_value, float):
            # insert a new row with the current date and time, e.g., 2014-03-06
            c2.execute('''INSERT INTO tenant_counter VALUES(?,?,?,?,?)''' , (actual_counter_id, save_time.strftime('%Y-%m-%d'), save_time.strftime('%H:%M:%S'), save_time.strftime('%Y-%m-%d %H:%M:%S'), sayac_value))
        else:
            # insert a new row with the current date and time, e.g., 2014-03-06
            c2.execute('''INSERT INTO tenant_counter VALUES(?,?,?,?,?)''' , (actual_counter_id, save_time.strftime('%Y-%m-%d'), save_time.strftime('%H:%M:%S'), save_time.strftime('%Y-%m-%d %H:%M:%S'), 'Error!'))
    conn2.commit()
    conn2.close()
    return

据我了解,在这里我只能在线程启动后每小时运行该代码。我该如何更改它,使其每天 23:30 后运行一次?对我来说,这段时间尤其重要。

最佳答案

我的建议是使用系统调度程序(Linux 上的 crontab),因为它就是为此目的而设计的。

如果 crontab 超出了您的范围,您必须保持脚本运行,并定期检查当前时间:

while True:
    now = datetime.datetime.now()
    # call the function between 23:30 and 23:35
    if now.hour == 23 and 30 <= now.minute <35:
       sayac_yaz()
    time.sleep(5*60)

关于python - 每天在Python中的指定时间后执行常规任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31921767/

相关文章:

xml - 如何使用 StreamXmlRecordReader 解析单个文件中的单行和多行 xml 记录

python - 同时处理 TCP 和 UDP 的 Twisted 协议(protocol)

python - 将转义字符写入文件

python - 通常使用哪种数据处理(内部或外部)?

python - 用两个 numpy 数组中的唯一值组合标记区域?

c++ - 是否可以在 [win-builder](http ://win-builder. r-project.org/) 上构建一个使用 Rcpp 和 Boost.Thread 的 R 包?

java - 事件派发线程如何工作?

python - Python 中的 Hadoop 流作业失败(不成功)

python - 在 cron 作业期间在子 shell 中引用 Python 3.7.3

iPhone "multi-threading"问题