简体   繁体   中英

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. Then, say that I run this program again at 10:01 and at 10:02. There's no guarantee that the instance run at 10:01 will be the first one to execute.

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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