简体   繁体   English

Python中程序实例的队列?

[英]Queue of instances of a program in Python?

Basically, I want to make it so that only one instance of my program can be run at once. 基本上,我想这样做,以便一次只能运行我的程序的一个实例。 A quick google search found this solution for preventing two instances of a program from running, which I adapted below to wait until the previous instance is finished before running. 谷歌快速搜索找到了一种解决方案,用于防止程序的两个实例运行,我在下面进行了调整,以等到前一个实例完成后再运行。

import fcntl, sys
pid_file = 'program.pid'
fp = open(pid_file, 'w')
while True:
    try:
        fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except IOError:
        # another instance is running
        continue
    break

However, this doesn't really respect the time at which a program was called. 但是,这并不真正尊重程序被调用的时间。

For example, say that I run this program at 10:00 and it goes for 5 minutes. 例如,假设我在10:00运行此程序,它将持续5分钟。 Then, say that I run this program again at 10:01 and at 10:02. 然后,说我在10:01和10:02再次运行该程序。 There's no guarantee that the instance run at 10:01 will be the first one to execute. 无法保证在10:01运行的实例将是第一个执行的实例。

I'd like to create a queue of runs by time, where the first call to the program made is the one that gets to run next. 我想按时间创建一个运行队列,在该队列中,对该程序的第一次调用是接下来要运行的那个。 Is there an easy solution to this? 有一个简单的解决方案吗? I could imagine every program writing/deleting its process ID to a log file on startup/completion and checking if it's next up in the log, but that seems kind of inelegant. 我可以想象每个程序在启动/完成时都将其进程ID写入/删除到日志文件中,并检查它是否紧接在日志中,但这似乎有点不雅。

I could imagin the following: 我可以想象以下内容:

PSEUDOCODE 伪代码

def Signal_Handler(signal):
    FIFO.push(signal.job_data)

def main(job_data):
  while True:
    process_Job(job_data)
    job_data = FIFO.pop()
    if not job_data:
        break

if __name__ == '__main__':
    job_data = sys.argv[1]
    if Lock_Programm():
        # First Instance
        Signal.Handler(SIG_USR1, Signal_Handler)
        main(job_data)
        Unlock_Programm()

    else:
        # Lock failed other Instance is running
        Signal.signal(SIG_USR1, job_data)
        exit(1)

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

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