2013-06-28 43 views
0

我已经问过类似于此的问题,但这一次它有点不同。对我来说,下面的代码应该可以工作。当前时间是特定的时候结束一个循环

import datetime 
# run infinitly 
while(True): 

    done = False 

    while(not done): 
    # 
    #main program 
    # 


    #stopping condition 
     if currenttime == '103000': 
     done = True 

    #continue with rest of program 

但是,它不会继续执行程序的其余部分,当它碰到上午10:30:00时。

下面的节目,我知道作品(在树莓PI):

import datetime 
done = False 
while not done: 
    currenttime = datetime.datetime.now().strftime('%H%M%S') 
    if currenttime != '103000': 
     print currenttime 
    if currenttime == '103000': 
     done = True 
print 'It is 10:30:00am, the program is done.' 

它使逻辑意义上给我什么,我在第一个例子。有谁知道为什么它不会退出该循环,并继续其余的?

+0

尝试冲出顶部代码位。例如,'currenttime'从哪里来? 10:30:00上午发生了什么? – wflynny

+1

时间作为停止条件不是一个好主意。 –

+0

如果没有看到程序的其余部分,就不可能说出来。并去了解http://linux.die.net/man/3/clock_gettime为什么你在做什么是一个坏主意。 – yaccz

回答

1

也许你需要设置当前时间,然后再检查?此外,if声明必须在103000处执行,以便执行done = True

while(True): 

    done = False 

    while(not done): 
    # 
    #main program 
    # 

    # need to set current time 
    currenttime = datetime.datetime.now().strftime('%H%M%S') 

    #stopping condition (use >= instead of just ==) 
     if currenttime >= '103000': 
     done = True 

    #continue with rest of program 
3

如果主程序需要较长的时间来运行,currenttime能跳从102958103005。因此完全跳过103000

+1

他总是可以有两次'old_time'和'cur_time'。然后做'如果old_time <103000和cur_time> 103000:done = True'。 – wflynny

1

请注意,并不保证您的循环在每个可用秒中都有一次迭代。系统负载越多,循环跳过的可能性就越大,这可能是终止标准。也有可能跳过秒的情况,例如,由于时间同步或夏令时问题。

而不是繁忙的等待循环,你可以预先计算timedelta在几秒钟内,然后睡了那么多秒。

优点:

  • 你可以节省你的机器上的其他进程可以使用,而不是计算能力。
  • 它可能会延长硬件的使用寿命。
  • 这也将更节能。

实施例:

import datetime 
import time 
def wait_until_datetime(target_datetime): 
    td = target_datetime - datetime.datetime.now() 
    seconds_to_sleep = td.total_seconds() 
    if seconds_to_sleep > 0: 
     time.sleep(seconds_to_sleep) 

target_datetime = datetime.datetime(2025, 1, 1) 
wait_until_datetime(target_datetime) 
print "Happy New Year 2025!" 

注意,这可能仍然无法产生所期望的行为,由于系统日期和时间设置的任意变化。或许最好采取完全不同的策略来在特定的时间执行特定的命令。您是否考虑过使用cron作业来实现所需的行为? (你可以将信号发送到进程,从而发出它取消循环...)

+0

对我的回答(http://stackoverflow.com/a/17353051/194586)与他的另一个问题类似的想法。时间以相当确定的速度流逝,没有理由不断地检查,好像当你等待的时间会让你感到惊讶。 –

0
import datetime 
done = False 
while True: 
    currenttime = datetime.datetime.now().strftime('%H%M%S') 
    if currenttime >= '103000': 
     break 
    print currenttime 
print 'It is 10:30:00am, the program is done.' 

如果你不能使用break:

import datetime 
done = False 
while not done: 
    currenttime = datetime.datetime.now().strftime('%H%M%S') 
    if currenttime >= '103000': 
     done = True 
    else: 
     print currenttime 
print 'It is 10:30:00am, the program is done.' 
相关问题