【问题标题】:How to run a python script that executes every 5 minutes BUT in the meantime executes some other script如何运行每5分钟执行一次但同时执行其他一些脚本的python脚本
【发布时间】:2020-06-19 08:12:59
【问题描述】:

我不希望代码在这 5 分钟内进入睡眠状态,只是等待。同时,我想运行一些其他代码块或脚本。
如何运行每 5 分钟执行一次的 python 脚本,但同时执行它代码块的其他一些脚本,直到再次达到 5 分钟时间。 例如我想运行 3 个函数。每 5 分钟运行一次。每 1 分钟再一次。每 10-20 秒再一次。

【问题讨论】:

标签: python time


【解决方案1】:

您可以使用Thread 来控制您的子进程并最终在 5 分钟后将其杀死

【讨论】:

    【解决方案2】:
    import time
    
    delay = 1 # time between your next script execution
    wait = delay
    t1 = time.time()
    
    while True:
       t2 = time.time() - t1
    
       if t2 >= wait:
          wait += delay
            # execute your script once every 5 minutes (now it is set to 1 second)
       # execute your other code here
    

    首先,您需要获取脚本的时间,然后您需要一个变量来存储脚本的“等待时间”(在本例中为“等待”)。

    每次您的脚本时间高于或等于“等待”时,都会添加延迟变量等待并执行代码。

    对于多次延迟,它是:

    import time
    
    delay = [1, 3]
    wait = [delay[0], delay[1]]
    t1 = time.time()
    
    while True:
       t2 = time.time() - t1
    
       for i in range(len(wait)):
           if t2 >= wait[i]:
               wait[i] += delay[i]
               if i==0:
                   print("This is executed every second")
               if i==1:
                   print("This is executed every 3 second")
    

    【讨论】:

    • 我认为最好释放分配的资源并让 cronjob 或其他操作系统调度来处理任务
    • 如果有两个以上执行时间不同的脚本呢?我有三个单独的脚本。每 5 分钟一次。每 1 分钟一次。每 10 秒再一次。
    • 对于不同的延迟,您需要一个列表“延迟”,列表“等待”。然后你会使用 for i in range(len(wait)) 或其他东西来检查脚本时间是否高于或等于每个“等待”值。我还建议你使用一个模块,但这是没有额外模块的方式。
    猜你喜欢
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 2011-07-20
    • 2014-03-25
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    相关资源
    最近更新 更多