Skip to content Skip to sidebar Skip to footer

How To Print Something At A Specific Time Of The Day

Is it possible to have python 2.7 print something at a specific time of the day. For example if I ran the program at 15:06 and coded it to print 'Do task now' at 15:07 it prints it

Solution 1:

I would suggest installing the library schedule, if you're able to.

Use pip install schedule

Your code would look like this if utilizing schedule:

import schedule
import time

def task():
    print("Do task now")

schedule.every().day.at("15:07").do(task)

while True:
    schedule.run_pending()
    time.sleep(1)

You can adjust time.sleep(1) as necessary to sleep for longer if a 1s interval is too long. Here is the schedule library page.

Solution 2:

If you're not using cron, then the general solution is to find the time remaining until you need the event to occur, have the program sleep for that duration, then continue execution.

The tricky part is to have the program find the next occurrence of a given time. There are some modules for this, but you could also do it with plain code for a well-defined case where it is only a fixed time of day.

import time

target_time = '15:07:00'
current_epoch = time.time()

# get string of full time and split it
time_parts = time.ctime().split(' ')
# replace the time component to your target
time_parts[3] = target_time
# convert to epoch
future_time = time.mktime(time.strptime(' '.join(time_parts)))

# if not in the future, add a day to make it tomorrow
diff = future_time - current_epoch
if diff < 0:
    diff += 86400

time.sleep(diff)
print'Done waiting, lets get to work'

Solution 3:

While python is not ideal to schedule something; there are better tools out there. Yet, if this is desired to be done in python below is a way to implement it:

Prints at scheduled_time of 11AM:

import datetime as dt
scheduled_time = dt.time(11,00,00,0)
while1==1:
    if (scheduled_time < dt.datetime.now().time() and 
       scheduled_time > (dt.datetime.now()- dt.timedelta(seconds=59)).time() ):
        print"Now is the time to print"break

There are two if conditions with an intent to print within one minute; a shorter duration can be chosen. But the break immediately after print ensures that print is executed only once.

You would need to extrapolate this so that code is run across days.

Refer: datetime Documentation

Post a Comment for "How To Print Something At A Specific Time Of The Day"