python定时执行脚本实例

本文提供三种定时任务的Python实现:一次性执行、周期性执行及无限循环执行。通过具体代码示例,介绍了如何使用Python标准库sched来安排任务,并探讨了不同场景下的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

定时任务代码实例

#coding=utf-8
#这里需要引入三个模块
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("ready to excute scrapt...") 
timming_exe("echo hello world", 10)

周期性执行实例

#coding=utf-8
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("ready to excute scrapt...") 
timming_exe("echo hello world", 10)

反复执行实例

#coding=utf-8
# 以需要的时间间隔执行某个命令 

import time, os 

def re_exe(cmd, inc = 60): 
    while True: 
        os.system(cmd); 
        time.sleep(inc) 

print("ready to excute scrapt...") 
re_exe("echo hello world", 10)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值