How To Run A Python Program At A Specific Time
HTML-код
- Опубликовано: 5 сен 2024
- In this video I cover how to run a python program or function at a specific time of day. This is useful when trying to call a function or program at a particular time. It has many use cases such as cron jobs.
Since I've always been warned against "while True" loops, you could make the "while" parameter dependent on the time:
while format_time != stop_time:
continue
print("The times matched")
I'm not sure how much memory it takes to look up the time continuously, but since you're only checking the time to the second:
from time import sleep
while format_time != stop_time:
sleep(1)
print("The times matched")
Great job! :)
Very insightful…
would appreciate if you could advise how to modify the script if i would like to stop/break the loop at min sec rather than sec. thanks in advance.
You can use the built in "time.sleep(60*minutes)" function at the end of the while loop after the if statement. Where "minutes" will be a variable that contains the amount of minutes you would like the program to check. I hope this has helped. :)
@@TaylorsSoftware sorry , i think you i did not write my question clearly. i am interested to stop/break at milliseconds (for example, stop time = 09:09:01.123456 ) rather than by second. hope you can help, thanks again.
I see now. I recommend you use the "datetime" module for microseconds rather than the "time" module, as it has more information. You can import datetime at the top of your program then set format_time = datetime.datetime.now().strftime("%H:%M:%S.%f"). I hope this helped! :)
@@TaylorsSoftware Hello again, the script has been modified but won't break at stop time. Do you know if I am missing anything here? Thanks
import time
import datetime
if __name__ == '__main__':
stop_time = "20:38:10.100000"
while 1:
# local_time = datetime.localtime()
format_time = datetime.datetime.now().strftime("%H:%M:%S.%f")
if(format_time == stop_time):
print("Time Matched")
break
print(format_time,end="
")
print("Loop broke")
@@TaylorsSoftware Hello Again,, the script was modified but seems it won't break at stop time. Do you think I missed anything here? Thanks again.
import time
import datetime
if __name__ == '__main__':
stop_time = "20:55:00.500000"
while 1:
# local_time = datetime.localtime()
format_time = datetime.datetime.now().strftime("%H:%M:%S.%f")
if(format_time == stop_time):
print("Time Matched")
break
print(format_time,end="
")
print("Loop broke")