zoukankan      html  css  js  c++  java
  • python脚本

    python定时任务
    1.time.sleep(n)
    循环执行,使用sleep阻塞n秒,缺点是sleep是个阻塞函数,会阻塞进程。

    import datetime
    import time
    def dosomething():
        while True:
            print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
            time.sleep(10)
    
    dosomething()
    print('end')
    

    运行结果:

    2.Timer(n, func)
    使用threading的Timer实现定时任务,Timer是非阻塞的。

    import datetime
    from threading import Timer
    def dosomething():
            print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
            Timer(10, dosomething).start()
    dosomething()
    print('end')
    

    运行结果:

    3.sched调度器
    shced模块是标准库定义的,它是一个调度器(延时处理禁止),将任务事件加入调度队列,调度器就会顺序执行

    import datetime
    import time
    import sched
    
    def dosomething():
            print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
            schedule.enter(10, 1, dosomething, ())
    
    # 生成调度器(两个参数比较复杂,暂不考虑含义)
    schedule = sched.scheduler(time.time, time.sleep)
    # 加入调度事件(间隔10秒执行,多个事件同时到达时优先级,触发的函数,函数参数)
    schedule.enter(10, 1, dosomething, ())
    # 运行
    schedule.run()
    
    print('end')
    

    运行结果:

    4.定时框架APScheduler(Advanced Python Scheduler)
    APScheduler是一个第三方库,使用很方便,支持间隔时间执行,固定时间执行,某个日期执行一次三种类型。

    import datetime
    from apscheduler.schedulers.blocking import BlockingScheduler
    
    def dosomething():
            print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    
    scheduler = BlockingScheduler()
    scheduler.add_job(dosomething, 'interval', seconds=10)
    scheduler.start()
    print('end')
    

    运行结果:

    5.windows定时任务
    可以使用pyinstaller将python程序打包成exe文件,然后添加到windows的定时任务。

    6.Linux定时任务
    可以使用Crontab定时运行python脚本。

  • 相关阅读:
    今天是JVM的生日,来了解下JVM的发展历史吧
    python 天天生鲜项目
    django中设置定时任务
    django-rest-framework视图和url
    rest_framework-分页
    rest_framework-序列化-1
    rest_framework-解析器
    django-rest-framework版本控制
    django-rest-framework限流
    django-rest-framework权限验证
  • 原文地址:https://www.cnblogs.com/shijingjing07/p/7573864.html
Copyright © 2011-2022 走看看