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

春季是一个富有生命力季节,也是一个美丽、神奇,充满希望季节。都说春季是花海洋。粉色淡雅,白色端庄,红色热烈,紫色深情,泼泼洒洒,浓浓烈烈。一朵朵花,把春季朝气蓬勃都开出来了。

本文实例讲述了Python实现定时执行任务的三种方式。分享给大家供大家参考,具体如下:

1.定时任务代码

#!/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)

2.周期性执行任务

#!/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)

3.循环执行命令

#!/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脚本监控华为AR路由器关键路由变化

Python自动化运维-netmiko模块设备自动发现

Python自动化运维—netmiko模块连接并配置华为交换机

Python自动化运维-利用Python-netmiko模块备份设备配置

Python3内置模块之json编码解码方法详解