【问题标题】:Doing a regular task after a specified time of day in Python everyday每天在 Python 中的指定时间后执行常规任务
【发布时间】:2015-08-10 14:07:05
【问题描述】:

我需要运行一些代码来存储我在每天 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

据我了解,在这里我只能在线程启动后每小时运行该代码。如何更改 ıt 以使其在每天 23:30 之后工作一次?对我来说,尤其是这个时间部分很重要。

【问题讨论】:

  • 如何使用 OS 调度程序? Unix 的 cron,Windows 的标准调度程序?这比编写自己的调度程序要好。
  • 但它在我的应用程序中是一个代码片段。而且我的应用程序没有按计划运行。只有那个片段。
  • 但您必须保持您的应用程序运行才能使其正常工作。使用 m9_psy 所写的 OS 调度程序是比重新发明轮子更好的解决方案...

标签: python multithreading python-2.7 parsing time


【解决方案1】:

我的建议是使用系统调度程序(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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-23
    • 2022-08-15
    • 2013-11-25
    • 2015-05-09
    • 2017-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多