Advertisement

python通过cron设置定时任务

阅读量:

python通过cron设置定时任务

  • 需要导入的包
    • 注意
    • 示例
    • 最后的最后,作为一名在测试领域仅积累两年经验的专业实习生,希望大家能给予我小小的鼓励和支持
    • 本人博客地址:stest.top

今天灵机一动尝试利用cron机制通过Python实现了一个定时任务;然而在寻找现成解决方案时耗尽了时间最终不得不逐一查阅官方文档(我的英语水平相当于二年级水平只能依靠翻译来理解)。

需要导入的包

为了实现模块化设计的目标(因为之前按照老方法操作总是遇到官方文档的"坑"(坑人),于是想着直接记录具体操作流程(怎么使用),但是一直没有整理出具体的模块化步骤(导致后来在谷歌上花了20多分钟才找到解决方案)

复制代码
    from apscheduler.schedulers.blocking import BlockingScheduler
    from apscheduler.triggers.cron import CronTrigger

注意

Python中的cron命令与标准cron存在差异。它直接去掉秒位,并且最后一位不能使用;需要用星号替代。

示例

复制代码
    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的相关内容。[链接]这篇文章。

最后的最后,在实习两年后,作为一名仅限于测试操作技能的测试实习生,希望各位大神能给予三连关注

本人博客地址:stest.top

全部评论 (0)

还没有任何评论哟~