简体   繁体   English

创建多个线程/进程以按计划执行各个 python 脚本

[英]Create multiple threads/processes to execute individual python scripts on schedule

I have multiple python files located in a local directory that I wish to run concurrently as separate threads or processes.我有多个 python 文件位于本地目录中,我希望作为单独的线程或进程同时运行。

As of right now, I have the following pseudocode截至目前,我有以下伪代码

def run_script(filePath, trigger):
   
    exec(open(filePath).read())

if __name__ == '__main__':
       for path in filePaths:
            proc = multiprocessing.Process(target=run_script, args=(path, trigger_sec))
            procs.append(proc)
            proc.start()

        for proc in procs:
            proc.join()

My question is: How do I add a scheduler/timer in the run_script function or somewhere else that tells the processes to exec that file every X seconds?我的问题是:如何在 run_script function 或其他告诉进程每 X 秒执行一次该文件的地方添加调度程序/计时器?

I haven't tested this, but you should look into using the time module.我没有对此进行测试,但您应该考虑使用time模块。 Try implementing something like this:尝试实现这样的事情:

import time


def run_script(filePath, wait, amount):
    # Runs a file 'amount' times and waits for 'wait' seconds before running
    for _ in range(amount):
        time.sleep(wait)
        file = open(filePath, 'r')
        exec(file.read())
        file.close()


if __name__ == '__main__':
       for path in filePaths:
            proc = multiprocessing.Process(target=run_script, args=(path, wait, amount))
            procs.append(proc)
            proc.start()

        for proc in procs:
            proc.join()

Don't forget to close the file after opening it.打开文件后不要忘记关闭文件。

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

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