Getting Started with Supervisor
After installing Supervisor, we need to know how to configure it. In this tutorial we are going to create a script and configure Supervisor to make sure that it is always running.
Create the Script
First let's create our example PHP script. For this example, the script is going to keep writing the time to a file. Instead of having the script run in an infinite loop, I'm going to just rely on supervisor restarting the script whenever it completes.
<?php $filepath = __DIR__ . '/the-time.txt'; $line = "The time is: " . time() . PHP_EOL; file_put_contents($filepath, $line); sleep(30);
Save the script somewhere on your server, perhaps under
sudo apt install php5-cli or
sudo apt install php7.0-cli
If you installed supervisor through the ubuntu packages, you need to create a configuration file at
/etc/supervisor/conf.d/myScript.conf which should have the following contents:
[program:MyScript] command=/usr/bin/php /path/to/script.php autorestart=true
If you installed supervisor through pip, you need to create a new file at
/etc/supervisord.conf with the following contents:
[supervisord] nodaemon=false [program:MyScript] command=/usr/bin/php /path/to/script.php autorestart=true
Set Configuration File Permissions
After having created the file, we need to change the permissions to 755 so that the supervisor application can read it.
sudo chmod 755 /etc/supervisor/conf.d/myScript.conf
Start Supervisor (Ubuntu 16.04 Users)
Finally, start supervisord to manage the specified processes.
sudo systemctl start supervisor
sudo systemctl enable supervisor
sudo systemctl restart supervisor
Now you should see that there is a file called
the-time.txt in the same directory as where you stored your PHP script, and it should always have one line in it with the unix timestamp of when the script started executing.
If you cannot see the
the-time.txt file in the same directory as your script I would double check the filepath specified in your supervisor configuration file, and then try running supervisor in the foreground if the path is correct.
This was a very basic demonstration of how you can use Supervisor, but hopefully it has shown you how useful it can be. I realize that in this specific example, you could have used a cron job instead, but there are certain scenarios where a cron job is not suitable.