Command line multithreading
我正在编写一个简单的命令行程序,显示当前时间并让用户设置警报。 但是,当raw_input阻止它时,警报没有响起。 我甚至实现了多线程,但它没有工作。 这是完整的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | import datetime, time, thread, os program_running = True now = datetime.datetime.now() alarm_status = 0 alarm_hour = 0 alarm_minute = 0 def clock(): now = datetime.datetime.now() print now.strftime('%H:%M') def set_alarm(): global alarm_hour, alarm_minute, alarm_status alarm_time = raw_input('Set Alarm (XX:XX) : ') alarm_hour = alarm_time[:alarm_time.find(':')] alarm_minute = alarm_time[alarm_time.find(':')+1:] alarm_status = 1 def alert_thread(): global alarm_hour, alarm_minute, alarm_status while True: if(alarm_status): if (str(now.hour) == str(alarm_hour) and str(now.minute) == str(alarm_minute)): print 'Ring.. Ring..' alarm_status = 0 #program start here thread.start_new_thread(alert_thread,()) while(program_running): now = datetime.datetime.now() print '1) Clock' print '2) Alarm' print '3) Quit' choice = input('Choose (1-6) : ') if(choice==1): clock() elif(choice==2): set_alarm() elif(choice==3): program_running = False |
我发现使用全局变量的实现只有一个线程用于警报有点奇怪。 这样,您始终只能设置一个警报,即使没有设置任何警报,也始终会有警报线程运行。 此外,您现在永远不会更新警报根本不应该运行。
也许考虑这样做。 这只是一个快速的重构,并不是说这是完美的,但它可以帮助你继续:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | import datetime, time, threading, os def clock(): now = datetime.datetime.now() print now.strftime('%H:%M') def set_alarm(): alarm_time = raw_input('Set Alarm (XX:XX) : ') alarm_hour = alarm_time[:alarm_time.find(':')] alarm_minute = alarm_time[alarm_time.find(':')+1:] alarm_thread = threading.Thread(target=alert_thread, args=(alarm_time, alarm_hour, alarm_minute)) alarm_thread.start() def alert_thread(alarm_time, alarm_hour, alarm_minute): print"Ringing at {}:{}".format(alarm_hour, alarm_minute) while True: now = datetime.datetime.now() if str(now.hour) == str(alarm_hour) and str(now.minute) == str(alarm_minute): print ("Ring.. Ring..") break #program start here while True: now = datetime.datetime.now() print '1) Clock' print '2) Alarm' print '3) Quit' choice = input('Choose (1-6) : ') if(choice==1): clock() elif(choice==2): set_alarm() elif(choice==3): break |
1 2 3 4 5 6 7 8 9 | from threading import Timer def ring(): print" Ring.. Ring.." t = Timer(3, ring) # ring in 3 seconds t.start() s = raw_input("wait for the ring, press enter afterwards") |
输出:
1 2 | wait for the ring, press enter afterwards.. Ring.. Ring.. |
2件事
就在线程的内部if之前,做
now = datetime.datetime.now()