Search code examples
pythonbashporttornado

How to start multiple tornado instance using bash


I have a tornado server and I would like to start multiple instances on different ports, so I created the following bash file to start 3 instances.

#!/bin/bash

#start tornado instances in different ports
python startup.py --port="8081"
python startup.py --port="8082"
python startup.py --port="8083"

As you can see, the above code is problematic, because the first command will block the second one. So anyone has any idea about how to start 3 together? Thanks in advance.


Solution

  • If you need to run them just in current session, add & at the end of each line:

    python startup.py --port="8081" &
    python startup.py --port="8082" &
    python startup.py --port="8083" &
    

    But it is much more convenient to use systemd, upstart or other init system, because it gives you an easy way to start, stop and restart your instances.

    If you need an example, i will update this answer.


    Update

    As long as you're using OS X, you can use default init system – launchd.

    Step 1 – create a config file for your job:

    vim /Library/LaunchDaemons/my_job.plist
    

    File contents:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
            <key>Label</key>
            <string>my.awesome.label</string>
    
            <key>ProgramArguments</key>
            <array>
                    <string>/usr/bin/python</string>
                    <string>/Users/ivanvinogradov/tort.py</string>
            </array>
    
            <key>OnDemand</key>
            <false/>
    
            <key>UserName</key>
            <string>ivanvinogradov</string>
    
            <key>StartInterval</key>
            <integer>60</integer>
    
            <key>StandardErrorPath</key>
            <string>/tmp/AlTest1.err</string>
    
            <key>StandardOutPath</key>
            <string>/tmp/AlTest1.out</string>
    </dict>
    </plist>
    

    Path to your .py script goes to <key>ProgramArguments</key>.
    Put name of user, who will run your job in <key>UserName</key> section.
    Also note that <key>Label</key> section is required.

    Step 2 – ensure that .plist file has appropriate permissions:

    sudo chown root:wheel /Library/LaunchDaemons/my_job.plist
    sudo chmod 600 /Library/LaunchDaemons/my_job.plist
    

    Step 3 – start and stop your job:

    sudo launchctl load -w /Library/LaunchDaemons/my_job.plist
    sudo launchctl unload /Library/LaunchDaemons/my_job.plist
    

    This is a very simple example of launchd. You can learn more about it here on SO or on an Apple doc page.