python 指定时间运行代码

一、如果想要在指定时间里运行某段代码,可以参考以下程序。

import time
from interval import Interval

while True:
    # 当前时间
    now_localtime = time.strftime("%H:%M:%S", time.localtime())
    # 当前时间(以时间区间的方式表示)
    now_time = Interval(now_localtime, now_localtime)
    print(now_time)

    time_interval = Interval("11:15:00", "15:50:00")
    print(time_interval)

    if now_time in time_interval:
        print("是在这个时间区间内")
        print("要执行的代码部分")

二、另一个代码固定时间间隔执行代码:

#引入time包
import time
#函数定义
def sleeptime(hour,min,sec):
 return hour*3600 + min*60 + sec
 
#设置自动执行间隔时间,我这里设置的2s
second = sleeptime(0,0,2)
#死循环
while True:
 #延时
 time.sleep(second)
 time.sleep(second)
 time.sleep(second)
 #执行
 print ("do action")

三、每天3点执行代码:

'''
Created on 2018-4-20

例子:每天凌晨3点执行func方法
'''
import datetime
import threading

def func():
    print("haha")
    #如果需要循环调用,就要添加以下方法
    timer = threading.Timer(86400, func)
    timer.start()

# 获取现在时间
now_time = datetime.datetime.now()
# 获取明天时间
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
# 获取明天3点时间
next_time = datetime.datetime.strptime(str(next_year)+"-"+str(next_month)+"-"+str(next_day)+" 03:00:00", "%Y-%m-%d %H:%M:%S")
# # 获取昨天时间
# last_time = now_time + datetime.timedelta(days=-1)

# 获取距离明天3点时间,单位为秒
timer_start_time = (next_time - now_time).total_seconds()
print(timer_start_time)
# 54186.75975


#定时器,参数为(多少时间后执行,单位为秒,执行的方法)
timer = threading.Timer(timer_start_time, func)
timer.start()

四、每天指定时间运行指定时间停止

from datetime import datetime, time
import multiprocessing
from time import sleep

# 程序运行时间在白天8:30 到 15:30  晚上20:30 到 凌晨 2:30
DAY_START = time(8, 30)
DAY_END = time(15, 30)

NIGHT_START = time(20, 30)
NIGHT_END = time(2, 30)


def run_child():
    while 1:
        print("正在运行子进程")


def run_parent():
    print("启动父进程")

    child_process = None  # 是否存在子进程

    while True:
        current_time = datetime.now().time()
        running = False  # 子进程是否可运行

        if DAY_START <= current_time <= DAY_END or (current_time >= NIGHT_START) or (current_time <= NIGHT_END):
            # 判断时候在可运行时间内
            running = True

        # 在时间段内则开启子进程
        if running and child_process is None:
            print("启动子进程")
            child_process = multiprocessing.Process(target=run_child)
            child_process.start()
            print("子进程启动成功")

        # 非记录时间则退出子进程
        if not running and child_process is not None:
            print("关闭子进程")
            child_process.terminate()
            child_process.join()
            child_process = None
            print("子进程关闭成功")

        sleep(5)


if __name__ == '__main__':
    run_parent()

Guess you like

Origin blog.csdn.net/qq_34717531/article/details/109157333