码迷,mamicode.com
首页 > 编程语言 > 详细

Python定时任务

时间:2018-08-12 17:12:21      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:__name__   python   print   timer   time()   thread   schedule   定时任务   read   

import threading
import time
import datetime

def exec_update():
    time.sleep(5)

def event_func():
    now_time = datetime.datetime.now().strftime(‘%Y-%m-%d %H:%M:%S‘)
    print(now_time)
    exec_update()
    t = threading.Timer(1, event_func)
    t.setDaemon(True)
    t.start()

if __name__ == ‘__main__‘:
    t = threading.Timer(0, event_func)
    t.setDaemon(True)
    t.start()
    while 1:
        pass

 

########################################################################################################

"""

定时任务,某个时间点执行

"""
import os
import time
import json
import sys
import sched
import signal
import datetime
import threading
import subprocess
from subprocess import DEVNULL
import service.db_conn as db_conn

#具体任务
def exec_update():

    print("update...")


#定时器
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()
    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()

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

Python定时任务

标签:__name__   python   print   timer   time()   thread   schedule   定时任务   read   

原文地址:https://www.cnblogs.com/frisk/p/9463196.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!