使用Python中的时间库制作例程

使用Python中的时间库制作例程,python,timer,Python,Timer,我编写这段代码的目的是最终为一些灯光创建一个定时例程。基本上有两个字段,用户填写这两个字段,分别表示灯什么时候亮,什么时候关。我现在从零地开始,所以我试着涵盖基本知识 我用另一篇文章中的代码下载了一个计时器: from datetime import datetime from threading import Timer x=datetime.today() y=x.replace(day=x.day, hour=1, minute=0, second=0, microsecond=0) d

我编写这段代码的目的是最终为一些灯光创建一个定时例程。基本上有两个字段,用户填写这两个字段,分别表示灯什么时候亮,什么时候关。我现在从零地开始,所以我试着涵盖基本知识

我用另一篇文章中的代码下载了一个计时器:

from datetime import datetime
from threading import Timer

x=datetime.today()
y=x.replace(day=x.day, hour=1, minute=0, second=0, microsecond=0)
delta_t=y-x

secs=delta_t.seconds+1

def hello_world():
    print "hello world"
    #...

t = Timer(secs, hello_world)
t.start()
它每天在特定的时间打印hello world。此代码的唯一问题是,一旦完成例程,它就不会重新启动。我想要一个持续提神的。除此之外,我想每秒打印一次时间。我尝试使用while循环,但最终被卡在那里,因此我的hello world语句从未实际打印:

from datetime import datetime
from threading import Timer

x=datetime.today()
y=x.replace(day=x.day+1, hour=1, minute=0, second=0, microsecond=0)
delta_t=y-x

secs=delta_t.seconds+1

def hello_world():
    print "hello world"
    #...

t = Timer(secs, hello_world)
t.start()

您可以使用run重新启动线程:

def hello_world():
   global t 
   print ("hello world")
   t.run()

t = Timer(secs, hello_world)
t.start()
这样你就可以做一条新的线了

  def hello_world():
       global sec
       print ("hello World")
       Timer(sec,hello_word).start()
您还可以使用CRON作业