前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python每天定时9点执行_python定时执行方法

python每天定时9点执行_python定时执行方法

作者头像
全栈程序员站长
发布2022-09-09 15:01:27
2.7K0
发布2022-09-09 15:01:27
举报
文章被收录于专栏:全栈程序员必看

大家好,又见面了,我是你们的朋友全栈君。

1 time.sleep

import time

for i in range(5):

print(i)

time.sleep(10)

2 用shed

copycode.gif
copycode.gif

import time

import sched

schedule = sched.scheduler ( time.time, time.sleep )

def func(string1,float1):

print(“now is”,time.time(),” | output=”,string1,float1)

print(time.time())

schedule.enter(2,0,func,(“test1”,time.time()))

schedule.enter(2,0,func,(“test1”,time.time()))

schedule.enter(3,0,func,(“test1”,time.time()))

schedule.enter(4,0,func,(“test1”,time.time()))

schedule.run()

print(time.time())

copycode.gif
copycode.gif

其中func中放要执行的函数,用schedule.enter加入要执行的函数,里面的第一个参数是延迟执行的时间,用sched.scheduler进行初始化

copycode.gif
copycode.gif

1512033155.9311035

now is 1512033157.9316308 | output= test1 1512033155.9311035

now is 1512033157.9316308 | output= test1 1512033155.9311035

now is 1512033158.9322016 | output= test1 1512033155.9311035

now is 1512033159.9316351 | output= test1 1512033155.9311035

1512033159.9316351

[Finished in 4.2s]

copycode.gif
copycode.gif

上面是执行结果,缺点是任务队列是阻塞型,即schedule里的任务不执行完,后面的主线程就不会执行

3 用threading里的timer,实现非阻塞型,即主线程要任务同时执行

copycode.gif
copycode.gif

import time

from threading import Timer

def print_time( enter_time ):

print “now is”, time.time() , “enter_the_box_time is”, enter_time

print time.time()

Timer(5, print_time, ( time.time(), )).start()

Timer(10, print_time, ( time.time(), )).start()

print time.time()

copycode.gif
copycode.gif

执行结果:

1512034286.9443169

1512034286.9452875

now is 1512034291.9460146 enter_the_box_time is 1512034286.9443169

now is 1512034296.9461012 enter_the_box_time is 1512034286.9452875

[Finished in 10.2s]

可看出任务和主线程是同步执行,但是后3位又稍有不同,应该是python的多线程并非真正的多线程导致

每天某个时间定时执行任务:

copycode.gif
copycode.gif

import datetime

import time

def doSth():

print(‘test’)

# 假装做这件事情需要一分钟

time.sleep(60)

def main(h=0, m=0):

”’h表示设定的小时,m为设定的分钟”’

while True:

# 判断是否达到设定时间,例如0:00

while True:

now = datetime.datetime.now()

# 到达设定时间,结束内循环

if now.hour==h and now.minute==m:

break

# 不到时间就等20秒之后再次检测

time.sleep(20)

# 做正事,一天做一次

doSth()

main()

copycode.gif
copycode.gif

4 linux用 crontab

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/160693.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档