简体   繁体   English

如何在整小时内激活 python 程序? (下午 12:00:00,上午 04:00:00)

[英]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.您可以在无限while循环中编写一个if条件来检查当前时间是否等于您的时间,例如(12:00:00pm,04:00:00am),或者您可以使用 sleep 方法,它会停止执行您的代码在指定的时间量内,您必须通过计算您的时间与当前时间之间的差来发现,这种方法不会像以前的方法那样消耗太多的 memory 和 cpu 周期。

I'd advise setting up a cron job to run your python program at specific time我建议设置一个 cron 作业以在特定时间运行您的 python 程序

for production i would add cron or schedule对于生产,我会添加 cron 或 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                

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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