You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
auto/utils/utils_daily_task_scheduler.py

64 lines
2.6 KiB

# -*- coding: utf-8 -*-
import os
import time
from datetime import datetime
"""
TaskScheduler 类用于管理定时任务的执行时间。
该类通过在指定的文件中存储时间戳来记录任务的上次执行时间和下次执行时间。
它提供了两个主要方法:load_start_time 和 save_start_time。
load_start_time 方法用于检查是否到达任务的执行时间,如果未到达则返回 0,否则返回上次执行时间。
save_start_time 方法用于更新下次执行时间,默认为当前时间加上指定的时间间隔(默认为 24 小时)。
Attributes:
file_path (str): 存储时间戳的文件路径。
time_span (int): 任务执行的时间间隔,默认为 86400 秒(24 小时)。
Methods:
load_start_time(): 检查是否到达任务的执行时间。
save_start_time(): 更新下次执行时间。
Example:
>>> scheduler = TaskScheduler("task_time.txt")
>>> last_start_time = scheduler.load_start_time()
>>> if last_start_time != 0:
>>> # 执行任务
>>> scheduler.save_start_time()
Note:
该类假设文件路径是有效的,并且有足够的权限进行读写操作。
如果文件不存在,将自动创建并写入当前时间戳。
"""
class TaskScheduler:
def __init__(self, file_path, time_span=86400):
self.file_path = file_path
self.time_span = time_span
def load_start_time(self):
timestamp_now = int(time.time())
start_time = 0
if not os.path.exists(self.file_path):
with open(self.file_path, "w") as file:
file.write(str(timestamp_now))
print('创建执行时间文件 {}'.format(datetime.fromtimestamp(timestamp_now).strftime('%Y-%m-%d %H:%M:%S')))
return timestamp_now
else:
with open(self.file_path, "r") as file:
start_time = int(file.read())
if start_time > timestamp_now:
print('任务未到执行时间, 下次执行时间: {}'.format(datetime.fromtimestamp(start_time).strftime('%Y-%m-%d %H:%M:%S')))
return 0
print('开始执行定时任务')
return start_time
def save_start_time(self):
timestamp_now = int(time.time())
date_now = datetime.fromtimestamp(timestamp_now).strftime('%Y-%m-%d %H:%M:%S')
# 时间戳 +24 小时
timestamp_now += self.time_span
print('写入下次执行时间: {}'.format(datetime.fromtimestamp(timestamp_now).strftime('%Y-%m-%d %H:%M:%S')))
with open(self.file_path, "w") as file:
file.write(str(timestamp_now))