简体   繁体   中英

How do I activate a python program at exact whole hours? (12:00:00pm, 04:00:00am)

I want to write a program that keeps running in the background and performs a certain task at each hour of the day. How do I achieve this?

You can write a if condition in a infinite while loop to check if current time is equals to your time say (12:00:00pm, 04:00:00am) or you can make use of the sleep method, it stops the exexution of your code for the specified amount of time, you must find that by calculating the difference between your time and the current time and this method does not consume much memory and cpu cycles like the previous method.

I'd advise setting up a cron job to run your python program at specific time

for production i would add cron or schedule


# Schedule Library imported
import schedule
import time
  
# Functions setup
def sudo_placement():
    print("Get ready for Sudo Placement at Geeksforgeeks")
  
def good_luck():
    print("Good Luck for Test")
  
def work():
    print("Study and work hard")
  
def bedtime():
    print("It is bed time go rest")
      
def geeks():
    print("Shaurya says Geeksforgeeks")
  
# Task scheduling
# After every 10mins geeks() is called. 
schedule.every(10).minutes.do(geeks)
  
# After every hour geeks() is called.
schedule.every().hour.do(geeks)
  
# Every day at 12am or 00:00 time bedtime() is called.
schedule.every().day.at("00:00").do(bedtime)
  
# After every 5 to 10mins in between run work()
schedule.every(5).to(10).minutes.do(work)
  
# Every monday good_luck() is called
schedule.every().monday.do(good_luck)
  
# Every tuesday at 18:00 sudo_placement() is called
schedule.every().tuesday.at("18:00").do(sudo_placement)
  
# Loop so that the scheduling task
# keeps on running all time.
while True:
  
    # Checks whether a scheduled task 
    # is pending to run or not
    schedule.run_pending()
    time.sleep(1)

Try this:

from datetime import datetime                  # Import datetime

def schedule(time, function):                  # Syntax:
    cur_time = datetime.strftime("%T")         # time: 24 hour time hh:mm:ss (09:00:00 or 21:00:00)
    if cur_time == time:                       # function: lampda: to_execute()
        function()   

def scheduled_function():
    print("TEST")

while True:
    schedule("15:00:00", lampda:scheduled_function()) # Schedule scheduled_function() to execute at 3:00 pm                

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM