Python实现定时执行任务的三种方式简单示例

洛溪
洛溪
发布时间:2026-10-13 | 4人浏览过
原创

本文介绍Python中实现定时执行任务的三种方法。通过sched模块的enter和run方法,可实现单次或周期性定时任务;同时提供基于while循环和time.sleep的简单重复执行方案。代码示例展示了如何指定命令与间隔时间,适合需要简单定时功能的Python开发者参考。

Python定时任务实现概述

本文通过具体示例,介绍在Python中实现定时执行任务的三种常见方式,供读者参考学习。

第一种方式:使用sched模块实现单次定时任务

方式一:单次定时任务执行


#!/user/bin/env python
# @Time   :2018/6/7 16:31
# @Author  :PGIDYSQ
#@File   :PerformTaskTimer.py
#定时执行任务命令
import time,os,sched
schedule = sched.scheduler(time.time,time.sleep)
def perform_command(cmd,inc):
  os.system(cmd)
  print('task')
def timming_exe(cmd,inc=60):
  schedule.enter(inc,0,perform_command,(cmd,inc))
  schedule.run()
print('show time after 2 seconds:')
timming_exe('echo %time%',2)

第二种方式:利用sched模块实现周期性循环任务

方式二:周期性定时任务执行


#!/user/bin/env python
# @Time   :2018/6/7 16:31
# @Author  :PGIDYSQ
#@File   :PerformTaskTimer.py
import time,os,sched
schedule = sched.scheduler(time.time,time.sleep)
def perform_command(cmd,inc):
  #在inc秒后再次运行自己,即周期运行
  schedule.enter(inc, 0, perform_command, (cmd, inc))
  os.system(cmd)
def timming_exe(cmd,inc=60):
  schedule.enter(inc,0,perform_command,(cmd,inc))
  schedule.run()#持续运行,直到计划时间队列变成空为止
print('show time after 2 seconds:')
timming_exe('echo %time%',2)

第三种方式:通过while循环与time.sleep实现简单重复执行

方式三:循环重复执行命令


#!/user/bin/env python
# @Time   :2018/6/7 16:31
# @Author  :PGIDYSQ
#@File   :PerformTaskTimer.py
import time,os
def re_exe(cmd,inc = 60):
  while True:
    os.system(cmd)
    time.sleep(inc)
re_exe("echo %time%",5)

如需了解更多Python相关知识,可参考本站专题:《Python日期与时间操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》。

希望上述内容能对您掌握Python程序设计有所帮助。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表