风雨同行 发表于 2024-8-15 13:55:36

Python实现定时使命的多种方式

一、循环sleep:

最简单的方式,在循环里放入要执行的使命,然后sleep一段时间再执行。缺点是,不容易控制,而且sleep是个壅闭函数
def timer(n):
    '''''
    每n秒执行一次
    '''
    while True:   
      print(time.strftime('%Y-%m-%d %X',time.localtime()))   
      yourTask()# 此处为要执行的任务   
      time.sleep(n)二、threading的Timer:

比方:5秒后执行
def printHello():
    print("start" )

Timer(5, printHello).start()比方:间隔5秒执行一次
def printHello():
    print("start" )
    timer = threading.Timer(5,printHello)
    timer.start()

if __name__ == "__main__":
    printHello()比方:两种方式组合用,5秒钟后执行,并且之后间隔5秒执行一次
def printHello():
    print("start")
    timer = threading.Timer(5,printHello)
    timer.start()

if __name__ == "__main__":
    timer = threading.Timer(5,printHello)
    timer.start()三、sched模块:

sched是一种调理(延时处理机制)。
import time
import os
import sched


# 初始化sched模块的scheduler类
# 第一个参数是一个可以返回时间戳的函数,第二个参数可以在定时未到达之前阻塞。
schedule = sched.scheduler(time.time, time.sleep)

# 被周期性调度触发的函数
def execute_command(cmd, inc):
    print('执行主程序')
   
    '''''
    终端上显示当前计算机的连接情况
    '''
    os.system(cmd)
    schedule.enter(inc, 0, execute_command, (cmd, inc))


def main(cmd, inc=60):
    # enter四个参数分别为:间隔事件、优先级(用于同时间到达的两个事件同时执行时定序)、被调用触发的函数,
    # 给该触发函数的参数(tuple形式)
    schedule.enter(0, 0, execute_command, (cmd, inc))
    schedule.run()


# 每60秒查看下网络连接情况
if __name__ == '__main__':
    main("netstat -an", 60)四、定时框架APScheduler:

APScheduler是基于Quartz的一个Python定时使命框架。提供了基于日期、固定时间间隔以及crontab范例的使命,并且可以长期化使命。
需要先安装apscheduler库,cmd窗口下令:pip install apscheduler
简单的间隔时间调理代码:
from datetime import datetime
import time
import os
from apscheduler.schedulers.background import BackgroundScheduler
#学习中遇到问题没人解答?小编创建了一个Python学习交流群:531509025

def tick():
    print('Tick! The time is: %s' % datetime.now())

if __name__ == '__main__':
    scheduler = BackgroundScheduler()
    # 间隔3秒钟执行一次
    scheduler.add_job(tick, 'interval', seconds=3)
    # 这里的调度任务是独立的一个线程
    scheduler.start()
    print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))
    try:
      # 其他任务是独立的线程执行
      while True:
            time.sleep(2)
            print('sleep!')
    except (KeyboardInterrupt, SystemExit):
      scheduler.shutdown()
      print('Exit The Job!')五、定时框架Celery:

非常强盛的分布式使命调理框架;
需要先安装Celery库,cmd窗口下令: pip install Celery
六、定时框架RQ:

基于Redis的作业队列工具,优先选择APScheduler定时框架;
七、使用windows的定时使命:

可以将所需要的Python步伐打包成exe文件,然后在windows下设置定时执行。
八、Linux的定时使命(Crontab):

在Linux下可以很方便的借助Crontab来设置和运行定时使命。进入Crontab文件编辑页面,设置时间间隔,使用一些shell下令来运行bash脚本或者是Python脚本,保存后Linux会自动按照设定的时间来定时运行步伐。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: Python实现定时使命的多种方式