2020-12-13

1.在一个死循环中,使用sleep()函数

1)每隔一定时间执行一次函数

from datetime import datetime
import time

‘’’
每个 10 秒打印当前时间。
‘’’
def timedTask():
while True:
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
time.sleep(10)

if name == ‘main’:
timedTask()
2)每天八点执行一次

import datetime
import threading

def func():
print(“haha”)
#如果需要循环调用,就要添加以下方法
timer = threading.Timer(86400, func)
timer.start()

获取现在时间

now_time = datetime.datetime.now()

获取明天时间

next_time = now_time + datetime.timedelta(days=+1)
next_year = next_time.date().year
next_month = next_time.date().month
next_day = next_time.date().day

获取明天8点时间

next_time = datetime.datetime.strptime(str(next_year)+"-"+str(next_month)+"-"+str(next_day)+" 08:00:00", “%Y-%m-%d %H:%M:%S”)

# 获取昨天时间

last_time = now_time + datetime.timedelta(days=-1)

获取距离明天8点时间,单位为秒

timer_start_time = (next_time - now_time).total_seconds()
print(timer_start_time)
while True:
func()
time.sleep(timer_start_time)
这种方法能够执行固定间隔时间的任务。如果timedTask()函数之后还有些操作,我们还使用死循环 + 阻塞线程。这会使得timedTask()一直占有 CPU 资源,导致后续操作无法执行。谨慎使用!

2.使用Python 标准库 threading 中的 Timer 类

from datetime import datetime
from threading import Timer
import time

‘’’
每个 10 秒打印当前时间。
‘’’
def timedTask():
‘’’
第一个参数: 延迟多长时间执行任务(单位: 秒)
第二个参数: 要执行的任务, 即函数
第三个参数: 调用函数的参数(tuple)
‘’’
Timer(10, task, ()).start()

定时任务

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

if name == ‘main’:
timedTask()
while True:
print(time.time())
time.sleep(5)

3.使用标准库中sched模块

①首先构造一个sched.scheduler类

它接受两个参数:timefunc和 delayfunc。timefunc 应该返回一个数字,代表当前时间,delayfunc 函数接受一个参数,用于暂停运行的时间单元。

一般使用默认参数就行,即传入这两个参数 time.time 和 time.sleep.当然,你也可以自己实现时间暂停的函数。

②添加调度任务

scheduler 提供了两个添加调度任务的函数:

enter(delay, priority, action, argument=(), kwargs={})

该函数可以延迟一定时间执行任务。delay 表示延迟多长时间执行任务,单位是秒。priority为优先级,越小优先级越大。两个任务指定相同的延迟时间,优先级大的任务会向被执行。action 即需要执行的函数,argument 和 kwargs 分别是函数的位置和关键字参数。

scheduler.enterabs(time, priority, action, argument=(), kwargs={})

③把任务运行起来

调用 scheduler.run()函数

from datetime import datetime
import sched
import time

‘’’
每个 10 秒打印当前时间。
‘’’
def timedTask():
# 初始化 sched 模块的 scheduler 类
scheduler = sched.scheduler(time.time, time.sleep)
# 增加调度任务
scheduler.enter(10, 1, task)
# 运行任务
scheduler.run()

定时任务

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

if name == ‘main’:
timedTask()
4.使用定时任务调度的库:schedule

import schedule
import time

def job():
print(“I’m working…”)

schedule.every(10).minutes.do(job)#每隔十分钟执行一次任务
schedule.every().hour.do(job)#每隔一小时执行一次任务
schedule.every().day.at(“10:30”).do(job)#每天的10:30执行一次任务
schedule.every(5).to(10).days.do(job)#每隔5到10天执行一次任务
schedule.every().monday.do(job)#每周一的这个时候执行一次任务
schedule.every().wednesday.at(“13:15”).do(job)#每周三13:15执行一次任务

while True:
schedule.run_pending()
time.sleep(1)
如果函数中带有参数

import schedule
import time

def job(name):
print("her name is : ", name)

name = '小明’
schedule.every(10).minutes.do(job, name)
schedule.every().hour.do(job, name)
schedule.every().day.at(“10:30”).do(job, name)
schedule.every(5).to(10).days.do(job, name)
schedule.every().monday.do(job, name)
schedule.every().wednesday.at(“13:15”).do(job, name)

while True:
schedule.run_pending()
time.sleep(1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值