Python定时任务

Posted 撒欢

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python定时任务相关的知识,希望对你有一定的参考价值。

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. ")
        while 1:
            time.sleep(1)
    except  Exception as e:
        print(e)



















































































以上是关于Python定时任务的主要内容,如果未能解决你的问题,请参考以下文章

Python下定时任务框架APScheduler的使用

python定时任务介绍

CentOS7 使用定时任务

Python 定时任务

apscheduler 定时任务框架

Python—定时任务