John D Giotta <jdgio...@gmail.com> wrote:
>  I'm looking to run a process with a limit of 3 instances, but each
>  execution is over a crontab interval. I've been investigating the
>  threading module and using daemons to limit active thread objects, but
>  I'm not very successful at grasping the documentation.
> 
>  Is it possible to do what I'm trying to do and if so anyone know of a
>  useful example to get started?

If you want a simple, cross platform way of doing it, then bind each
process to a different local tcp port.

Make a list of 3 ports, and try binding to each port in turn.  If you
can't find a port to bind to then there are already 3 instances
running.

Something like this

import socket
PORTS = range(10000,10003)
lock_sock = None

def lock_process(_locks = []):
    for port in PORTS:
        sock = socket.socket()
        try:
            sock.bind(("localhost", port))
        except socket.error, e:
            sock = None
        else:
            _locks.append(sock)
            break
    else:
        raise Exception("Too many instances of me running")

for i in range(5):
    print "Trying",i+1
    lock_process()


Which prints

Trying 1
Trying 2
Trying 3
Trying 4
Traceback (most recent call last):
  File "<stdin>", line 20, in <module>
  File "<stdin>", line 16, in lock_process
Exception: Too many instances of me running

You could do the same thing with lock files also very easily...


-- 
Nick Craig-Wood <n...@craig-wood.com> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to