python通过cron设置定时任务

今天突发奇想使用通过cron用python设置一个定时任务,不过找了半天在百度中直接使用的案例,最后一点一点的查官方文档才找到(我这英语水平为2年级的渣渣,全靠翻译.)

需要导入的包

需要使导入包(写到这就想起来官方文档坑人,就写怎么使用了,没有写需要导入什么包,最后在谷歌上找了20多分钟才找到)
需要使用pip install apscheduler 安装所需要的包,然后导入

from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers.cron import CronTrigger

注意

python使用的cron与标准的cron有所区别,他只有5位
他直接去掉和秒并且最后一位不能使用? 需要使用*代替

示例

from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers.cron import CronTrigger
import os
import time
import shutil


# 删除存放30天的文件
def delFiles(dir_path, beforeDay="30"):
    """
    :param dir_path: 文件路径
    :param beforeDay: 需要删除的天数
    :return:
    """
    beforeDay = int(beforeDay)
    beforeSec = time.time() - 3600 * 24 * beforeDay
    for i in os.listdir(dir_path):
        filepath = "%s%s%s" % (dir_path, os.sep, i)
        if os.path.getmtime(filepath) < beforeSec:
            try:
                if os.path.isfile(filepath):
                    os.remove(filepath)
                else:
                    shutil.rmtree(filepath)
            except Exception as e:
                print(e)


def times():
    print(time.strftime("%Y-%m-%d-%H_%M_%S", time.localtime()))

dir_path=r'E:\桌面\民宿'
# 5位的cron是从分钟开始计算,最后一位不能使用?需要使用*代替,times与delFiles是需要调用的函数名
sched = BlockingScheduler()
sched.add_job(times, CronTrigger.from_crontab('0/10 * * * *'))
# 删除30天前的文件
# args用于函数中进行传值,可以随机命名,只需要在后面传递参数即可
sched.add_job(delFiles, CronTrigger.from_crontab('0 0 1/30 * *'), args=(dir_path, "30"))

其他参数可以参考:花10分钟让你彻底学会Python定时任务框架apscheduler这篇文章

最后的最后,作为一个实习2年只会点点的测试实习生,请各位大佬来波关注三连

本人博客地址:stest.top


版权声明:本文为weixin_44617502原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。