Advertisement

Python为定时任务提供了八种方案!

阅读量:

利用 while True: + sleep() 实现定时任务

time 模块中包含的 sleep(secs) 函数,能够使当前运行的线程在指定的 secs 秒内处于暂停状态,随后再继续执行。这里的暂停意味着将当前线程转为阻塞状态,待 sleep() 函数设定的时间到达后,线程会从阻塞状态转变为就绪状态,从而等待 CPU 的调度。

借助这一功能,我们可以通过结合 while 死循环与 sleep() 函数的方式,实现基础的定时任务操作。

代码示例:

复制代码
 import datetime

    
  
    
 import time
    
  
    
 def time_printer():
    
  
    
     now = datetime.datetime.now()
    
  
    
     ts = now.strftime('%Y-%m-%d %H:%M:%S')
    
  
    
     print('do func time :', ts)
    
  
    
 def loop_monitor():
    
  
    
     while True:
    
  
    
         time_printer()
    
  
    
         time.sl

全部评论 (0)

还没有任何评论哟~