Python定時任務

來源:互聯網
上載者:User

標籤:__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定時任務

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.