手机版
你好,游客 登录 注册
背景:
阅读新闻

Python3定时器任务代码

[日期:2019-09-24] 来源:Linux社区  作者:frisk [字体: ]

使用threading写的一个定时器任务demo:

import time
import sys
import signal
import datetime
import threading


#定时器
def schedule_update():
    t = threading.Timer(0, event_func)
    t.setDaemon(True)
    t.start()

#执行函数
def event_func():
    now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    print(now_time)
    exec_update()
    #update_openvas_dbs_from_cache()
    interval_time = delay_time()
    t = threading.Timer(interval_time, event_func)
    t.setDaemon(True)
    t.start()

#取时间点
def delay_time():
    # now time
    now_time = datetime.datetime.now()
    # tomorrow time
    next_time = now_time + datetime.timedelta(days=+1)
    next_year = next_time.date().year
    next_month = next_time.date().month
    next_day = next_time.date().day
    # get tomorrow 00:00
    next_time = datetime.datetime.strptime(str(next_year)+"-"+str(next_month)+"-"+str(next_day)+" 00:00:00", "%Y-%m-%d %H:%M:%S")

    # get secondes
    delay_time = (next_time - now_time).total_seconds()
    return delay_time

def quit_sys(signum, frame):
    sys.exit()

#接收C
if __name__ == "__main__":
    try:
        signal.signal(signal.SIGINT, quit_sys)
        signal.signal(signal.SIGTERM, quit_sys)
        schedule_update()
        print("schedule_update server starting up...\nHit Ctrl-C to quit.\n")
        while 1:
            time.sleep(1)
    except  Exception as e:
        print(e)

更多Python相关信息见Python 专题页面 https://www.linuxidc.com/topicnews.aspx?tid=17

Linux公社的RSS地址https://www.linuxidc.com/rssFeed.aspx

本文永久更新链接地址https://www.linuxidc.com/Linux/2019-09/160795.htm

linux
相关资讯       Python3定时器 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款