Running a Script in the Background and Scheduling with nohup
Running scripts in the background and scheduling them to execute at specific intervals can be essential for various tasks, such as periodic data processing, backups, or automated jobs. In this tutorial, we will explore how to achieve this using the nohup
command and a simple bash script.
Prerequisites
Before we begin, ensure you have the following:
- A script that you want to run periodically.
- A basic understanding of bash scripting.
- Access to a Unix-like environment (Linux or macOS).
Step 1: Create a Bash Script
First, create a bash script that includes the logic for your task. For this tutorial, we’ll create a script (your_script_runner.sh
) that runs another script (your_script.py
) every 5 seconds, starting 5 seconds after every minute.
#!/bin/bash
while true; do
current_second=$(date +%S)
if [ $current_second -eq 5 ]; then
python your_script.py
fi
sleep 1
done
Save this script in your working directory.
Step 2: Make the Script Executable
Make the script executable using the following command:
chmod +x your_script_runner.sh
Step 3: Run the Script with nohup
Now, run the script in the background using nohup
:
nohup ./your_script_runner.sh > /dev/null 2>&1 &
The nohup
command ensures that the script continues running even after you close the terminal. The > /dev/null 2>&1
redirects both standard output and standard error to /dev/null
, preventing the creation of nohup.out
with unnecessary messages.
Step 4: Monitor Script Output (Optional)
If you want to monitor the script’s output, you can check the contents of nohup.out
:
cat nohup.out
To follow the output in real-time, you can use the tail
command:
tail -f nohup.out
Step 5: Stop the Script
To stop the script, find its Process ID (PID) using ps
or pkill
and use the kill
command:
kill <PID>
pkill -f your_script_runner.sh
To find the task id:
ps aux | grep your_script_runner.sh
Conclusion
In this tutorial, we’ve explored how to run a script in the background nohup
and schedule it to run at specific intervals. This approach is useful for automating repetitive tasks and ensuring they continue running even after you've closed the terminal.
Remember to adapt the script and scheduling logic according to your specific requirements and to handle potential resource constraints based on the nature of your task.