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

yipeiwu_com5年前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字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

python MNIST手写识别数据调用API的方法

python MNIST手写识别数据调用API的方法

MNIST数据集比较小,一般入门机器学习都会采用这个数据集来训练 下载地址:yann.lecun.com/exdb/mnist/ 有4个有用的文件: train-images-idx3...

python 实现一个反向单位矩阵示例

python 实现一个反向单位矩阵示例

反向单位矩阵 单位矩阵即对角线为 1,如下: ​ 那么反向的单位矩阵就是反对角线为 1: ​ 左右镜像操作 这里采用 numpy 实现。 方案 1 imp...

Python用UUID库生成唯一ID的方法示例

UUID介绍 UUID是128位的全局唯一标识符,通常由32字节的字符串表示。它可以保证时间和空间的唯一性,也称为GUID,全称为:UUID —— Universally Unique...

django自带serializers序列化返回指定字段的方法

django orm 有个defer方法,指定模型排除的字段。 如下返回的Queryset, 排除‘username', 'id'。 users=models.UserInfo.ob...

python截取两个单词之间的内容方法

1. __init__ 初始化文件路径,关键字1,关键字2; 2. key_match 使用with open 方法,以二进制方式(也可以改成utf-8,GB2312)读取文件内容(支持...