python 时间控制的几种方式

    科技2026-10-04  3

    https://blog.csdn.net/qq_36867011/article/details/86533326

     

    第一种: #================================================================= #先等待10分钟后再执行,每1小时后执行一次 ##================================================================= import threading def printHello():     print("运行程序")     timer = threading.Timer(3600, printHello)  #每小时=3600秒     timer.start()     print("运行程序2") # if __name__ == "__main__":     timer = threading.Timer(6, printHello)  #10分钟=600秒,表示10分钟后启动一个线程运行本程序     timer.start()

     

    第二种:   #=================================================================== #每隔60秒运行一次 #=================================================================== import time,os def re_exe(inc = 60):  #缺省时间为60秒     while True:         print('运行时间')         time.sleep(inc) re_exe(60)

     

    第三种   #================================================================== #周期性任务, #================================================================== import sched,time,os 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):     schedule.enter(inc,0,perform_command,(cmd,inc))     schedule.run()#持续运行,直到计划时间队列变成空为止 print('show time after 2 seconds:') timming_exe('echo %time%',2)

    第四种:

    #====================================

    #计算某程序的执行时间,测试时经常用到。  #================================== import time def func():     p = 1     for i in range(1,100000):         p = p * i     return p startTime = time.time() result = func() endTime = time.time() print('The result is %s digit long.'%(len(str(result)))) print('运行时间为%s秒'%(endTime - startTime))

     

    第五种:每天如何定时启动爬虫任务   import datetime import time   def doSth():     # 把爬虫程序放在这个类里     print(u'这个程序要开始疯狂的运转啦')   # 一般网站都是1:00点更新数据,所以每天凌晨一点启动 def main(h=1,m=0):     while True:         now = datetime.datetime.now()         # print(now.hour, now.minute)         if now.hour == h and now.minute == m:             doSth()         # 每隔60秒检测一次         time.sleep(60)    

    第六种: # #====================================== #  简单实用的定时任务 # #====================================== import schedule import time   def job(name='ssss'):     print("I'm working...",name) schedule.every(10).minutes.do(job) schedule.every().hour.do(job) schedule.every().day.at("10:30").do(job) schedule.every(5).to(10).days.do(job) schedule.every().monday.do(job) schedule.every().friday.at("02:45").do(job,'name') while True:     schedule.run_pending()     time.sleep(1)

    Processed: 0.018, SQL: 9