首页 > 解决方案 > Script to wait till a specified time

问题描述

Wait till Specified Time

I need the best way to halt a program until the specified time is mentioned(in variable wait_time a tuple of hours, minutes, seconds). I had tried to use while loop for this. But is there a more efficient way for this such that it doesn't take much of the CPU. After waiting it does a function called solve().

wait_time=(12,10,15)
import time
time_str=time.localtime()
current_time=(time_str.tm_hour,time_str.tm_min,time_str,time_str.tm_sec)
while current_time!=wait_time:
    current_time=(time_str.tm_hour,time_str.tm_min,time_str,time_str.tm_sec)
else:
    print('Wait time over')
    solve()

I require a more efficient way than this for the memory part. It should wait until the system time is the time given.

标签: pythontimewhile-loopwait

解决方案


I have hacked together a method that should work for you:

timeWait.py
import time

def waitTime(hrs, mins, secs):
    totalTime = ((hrs * 3600) + (mins * 60) + secs) # this is the time to wait in seconds
    time.sleep(totalTime) # time.sleep() sleeps for a given number of seconds
Using it in the shell:
Python 3.8.0 (v3.8.0:fa919fdf25, Oct 14 2019, 10:23:27) 
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeWait 
>>> timeWait.waitTime(1, 23, 42)
# This will wait/sleep for 1 hour, 23 minutes, and 42 seconds.
How you can use it in your program:
import time

def waitTime(hrs, mins, secs):
    totalTime = ((hrs * 3600) + (mins * 60) + secs)
    time.sleep(totalTime)

waitTime(12, 10, 15)
# The following code will run when the time is up
print('Wait time over')
solve()

推荐阅读