Python:在特定(灵活的)时间点执行命令

2024-10-01 07:49:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图让python脚本在特定时间执行两个命令。通常我只使用cron,但是命令需要在每天不同的时间执行。你知道吗

到目前为止,我已经创建了一个while循环,反复运行时间检查函数:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime     
import time         

x = -1 # for loop

def Zeitcheck():
   currentTime = datetime.datetime.now().strftime('%H:%M') 


   if currentTime == time1:
       # command to run goes here
       time.sleep(55)
       return

   elif currentTime == time2:
       # command to run goes here
       time.sleep(55)
       return

   else:
       print currentTime
       time.sleep(55)
       return

while x == -1:
Zeitcheck()

(time1和time2的值来自外部文件)

脚本可以工作,但是这个时间循环似乎不是处理这个问题的最佳方法。有没有更优雅的解决方案?谢谢!你知道吗


Tags: torunimport命令脚本datetimereturntime