定时任务代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#coding=utf-8 """ auth py40.com 定时执行某个任务 """ #这里需要引入三个模块 import time, os, sched # 第一个参数确定任务的时间,返回从某个特定的时间到现在经历的秒数 # 第二个参数以某种人为的方式衡量时间 schedule = sched.scheduler(time.time, time.sleep) def perform_command(cmd, inc): os.system(cmd) def timming_exe(cmd, inc = 60): # enter用来安排某事件的发生时间,从现在起第n秒开始启动 schedule.enter(inc, 0, perform_command, (cmd, inc)) # 持续运行,直到计划时间队列变成空为止 schedule.run() print("show time after 10 seconds:") timming_exe("echo %time%", 10) |
周期性执行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#coding=utf-8 """ auth py40.com 周期性执行实例 """ 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): # enter用来安排某事件的发生时间,从现在起第n秒开始启动 schedule.enter(inc, 0, perform_command, (cmd, inc)) # 持续运行,直到计划时间队列变成空为止 schedule.run() print("show time after 10 seconds:") timming_exe("echo %time%", 10) |
循环执行命令
1 2 3 4 5 6 7 8 9 10 11 12 |
#coding=utf-8 """ 循环执行某个命令 """ import time, os def re_exe(cmd, inc = 60): while True: os.system(cmd); time.sleep(inc) re_exe("echo %time%", 5) |
未经允许不得转载:Python在线学习 » python定时执行任务命令