python脚本

python定时任务
1.time.sleep(n)
循环执行,使用sleep阻塞n秒,缺点是sleep是个阻塞函数,会阻塞进程。

import datetime
import time
def dosomething():
    while True:
        print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        time.sleep(10)

dosomething()
print('end')

运行结果:

2.Timer(n, func)
使用threading的Timer实现定时任务,Timer是非阻塞的。

import datetime
from threading import Timer
def dosomething():
        print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        Timer(10, dosomething).start()
dosomething()
print('end')

运行结果:

3.sched调度器
shced模块是标准库定义的,它是一个调度器(延时处理禁止),将任务事件加入调度队列,调度器就会顺序执行

import datetime
import time
import sched

def dosomething():
        print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        schedule.enter(10, 1, dosomething, ())

# 生成调度器(两个参数比较复杂,暂不考虑含义)
schedule = sched.scheduler(time.time, time.sleep)
# 加入调度事件(间隔10秒执行,多个事件同时到达时优先级,触发的函数,函数参数)
schedule.enter(10, 1, dosomething, ())
# 运行
schedule.run()

print('end')

运行结果:

4.定时框架APScheduler(Advanced Python Scheduler)
APScheduler是一个第三方库,使用很方便,支持间隔时间执行,固定时间执行,某个日期执行一次三种类型。

import datetime
from apscheduler.schedulers.blocking import BlockingScheduler

def dosomething():
        print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))

scheduler = BlockingScheduler()
scheduler.add_job(dosomething, 'interval', seconds=10)
scheduler.start()
print('end')

运行结果:

5.windows定时任务
可以使用pyinstaller将python程序打包成exe文件,然后添加到windows的定时任务。

6.Linux定时任务
可以使用Crontab定时运行python脚本。

原文地址:https://www.cnblogs.com/shijingjing07/p/7573864.html