import os import time import datetime import shutil from apscheduler.schedulers.blocking import BlockingScheduler path = r'D:\zwj\word_uploads' def del_flie(): # 获取文件夹下所有文件和文件夹 files = os.listdir(path) files.sort(key=lambda x: int(x)) # 从小到大排列 print(files) tody_time = datetime.datetime.now().date().strftime('%Y-%m-%d') before_10_days = (datetime.datetime.now() + datetime.timedelta(days=-10)).date().strftime('%Y-%m-%d') for file in files: file_path = os.path.join(path, file) # 文件最后一次修改的时间 file_time = time.strftime('%Y-%m-%d', time.localtime(os.stat(file_path).st_mtime)) # 判断是否是文件,这里直接删除文件夹就可以了 if file_time < before_10_days: # 比较时间即可,保留10天的文件 if os.path.isfile(file_path): # print('phy_uploads的子文件中存在文件', file, '-----',file_time) # 删除过期文件 os.remove(file_path) elif os.path.isdir(file_path): # 如果是文件夹,继续遍历删除 shutil.rmtree(file_path) # 递归删除文件夹,会把phy_uploads整个文件夹都给删了 print(file_path + " was removed!") # def dojob(): # # 创建调度器:BlockingScheduler # scheduler = BlockingScheduler() # now_time = str(datetime.datetime.now().time())[:2] # while True: # if int(now_time) >= 13 or int(now_time) <= 5: # # 添加任务,时间间隔7天 # scheduler.add_job(del_flie, 'interval', days=7) # 阻塞方式,每隔7days执行一次,刚启动时不执行 # scheduler.start() def dojob(): # 创建调度器:BlockingScheduler scheduler = BlockingScheduler() # 添加任务,时间间隔7天 scheduler.add_job(del_flie, 'interval', days=7, start_date='2020-11-01 01:00:00') # 阻塞方式,每隔7days执行一次,刚启动时不执行 # scheduler.add_job(del_flie, "cron", day_of_week = "7", hour = 1, minute = 0) scheduler.start() if __name__ == '__main__': print("\n--------delete file process is start--------\n") dojob()