python 实现 定时运行程序 time、datetime函数

1.time模块

使用 Python 的 time 模块来实现定时运行。 例如,你可以使用 time.sleep() 函数来让程序暂停一段时间,然后使用 time.time() 函数来获取当前时间戳。

import time

def run_task():
    # 执行你想要定时运行的代码
    print('Task running at:', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))

# 设置时间间隔(以秒为单位)
interval = 60

# 获取当前时间戳
current_time = time.time()

# 计算下一次运行的时间戳
next_run_time = current_time + interval

while True:
    # 获取当前时间戳
    current_time = time.time()

    # 如果当前时间戳大于或等于下一次运行的时间戳,则运行任务
    if current_time >= next_run_time:
        run_task()
        # 计算下一次运行的时间戳
        next_run_time = current_time + interval
    else:
        # 否则,暂停程序
        time.sleep(1)

该代码会每隔 60 秒运行一次 run_task 函数。你可以根据需要更改 interval 的值来调整时间间隔。

如果你想设置一个固定的开始时间,你可以使用 time.struct_time 类型表示的时间来替换上面示例中的 current_time 变量。例如:

import time

def run_task():
    # 执行你想要定时运行的代码
    print('Task running at:', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))

# 设置时间间隔(以秒为单位)
interval = 60

# 获取固定的开始时间
start_time = time.strptime('2022-12-27 15:00:00', '%Y-%m-%d %H:%M:%S')

# 将开始时间转换为时间戳
start_time_stamp = time.mktime(start_time)

# 计算下一次运行的时间戳
next_run_time = start_time_stamp + interval

while True:
    # 获取当前时间戳
    current_time = time.time()

    # 如果当前时间戳大于或等于下一次运行的时间戳,则运行任务
    if current_time >= next_run_time:
        run_task()
        # 计算下一次运行的时间戳
        next_run_time = current_time + interval
    else:
        # 否则,暂停程序
        time.sleep(1)

这段代码会在 2022 年 12 月 27 日 15:00:00 开始运行,然后每隔 60 秒运行一次 run_task 函数。你可以根据需要更改 interval 的值来调整时间间隔,以及更改 start_time 的值来调整开始时间。

2.datetime模块

如果你使用的是 Python 3.7 及更高版本,你还可以使用 datetime 模块来实现定时运行。例如,你可以使用 datetime.datetime.now() 函数来获取当前时间,然后使用 datetime.timedelta 类型来计算下一次运行的时间。

import time
from datetime import datetime, timedelta

def run_task():
    # 执行你想要定时运行的代码
    print('Task running at:', datetime.now().strftime('%Y-%m-%d %H:%M:%S'))

# 设置时间间隔(以秒为单位)
interval = 60

# 获取固定的开始时间
start_time = datetime.strptime('2022-12-27 15:00:00', '%Y-%m-%d %H:%M:%S')

# 计算下一次运行的时间
next_run_time = start_time + timedelta(seconds=interval)

while True:
    # 获取当前时间
    current_time = datetime.now()

    # 如果当前时间大于或等于下一次运行的时间,则运行任务
    if current_time >= next_run_time:
        run_task()
        # 计算下一次运行的时间
        next_run_time = current_time + timedelta(seconds=interval)
    else:
        # 否则,暂停程序
        time.sleep(1)

这段代码会在 2022 年 12 月 27 日 15:00:00 开始运行,然后每隔 60 秒运行一次 run_task 函数。你可以根据需要更改 interval 的值来调整时间

猜你喜欢

转载自blog.csdn.net/weixin_42984235/article/details/128451743