Running programs indefinitely ensures that services and applications are always available, reliable, and capable of handling real-time data and tasks effectively. So People often want to run programs indefinitely on computers.
In Linux, if you have root access, you can use systemctl
to manage services and ensure that they run continuously. Without root access, you can use pm2
, a process manager for Node.js applications, to keep programs running. Here’s how you can use both methods:
Using systemctl
(with root access)
Create a service file:
Create a new service file in /etc/systemd/system/
, for example, myprogram.service
.
[Unit]
Description=My Program
After=network.target
[Service]
ExecStart=/path/to/your/program
Restart=always
User=your-username
WorkingDirectory=/path/to/working-directory
[Install]
WantedBy=multi-user.target
Reload the systemd daemon:
sudo systemctl daemon-reload
control the service:
sudo systemctl start|stop|restart|status myprogram.service
Enable the service to start on boot:
sudo systemctl enable myprogram.service
Using pm2
(without root access)
Install pm2
:
If pm2
is not already installed, you can install it using npm:
npm install pm2 -g
Start your program with pm2
:
pm2 start /path/to/your/program --name myprogram
Ensure pm2
restarts your program on system reboot:
pm2 save
pm2 resurrect //create a cron job @reboot
Both tools ensure that your program runs continuously and can be set to start automatically on system boot.
here’s a table comparing systemctl
and pm2
:
Feature | systemctl | pm2 |
---|---|---|
Access Level | Requires root access | Does not require root access |
Installation | Built-in on most Linux distributions | Requires installation via npm |
Service Management | System-level service management | User-level process management |
Configuration | Service files in /etc/systemd/system/ | Managed through pm2 CLI |
Startup Script Creation | Manual setup in service file | pm2 startup command |
Process Monitoring | Systemd handles restarts and monitoring | pm2 handles restarts and monitoring |
Automatic Restart on Failure | Yes | Yes |
Logs Management | Journald (using journalctl to view logs) | Built-in logging and monitoring (pm2 logs ) |
Run at Boot | systemctl enable | pm2 save + pm2 startup |
Multi-user Support | Yes | Yes |
Ease of Use | Requires knowledge of systemd units | Simple and intuitive CLI |
Application Type | Any (general-purpose) | Mainly for Node.js apps but supports others |
Web Interface | No | Yes (pm2-gui for a web dashboard) |
Community and Documentation | Extensive documentation | Extensive documentation and active community |
Additional Features | Timers, targets, and dependencies support | Load balancing, clustering, and more |