# LLM response of the question "How do I make a Linux system go to sleep after the average system load is under a certain threshold?" ## Table of contents [TOC] ## Model Gemini 2.5 Flash Preview 05-20 ## Response Making a Linux system go to sleep (suspend-to-RAM) based on average system load requires a script that continuously monitors the load and then initiates the suspend action when conditions are met. This is a common way to save power on servers or desktops that aren't always busy. Here's a comprehensive guide to set this up, including the script and how to run it reliably using systemd. ### Understanding Load Average The "load average" in Linux represents the average number of processes that are either running or waiting to run (in an uninterruptible state). It's typically shown as three numbers: 1-minute, 5-minute, and 15-minute averages. For this purpose, the **5-minute average** is usually a good balance between responsiveness and stability. A load average of 1.00 on a single-core CPU means the CPU is fully utilized. On a multi-core CPU, 1.00 means one core is fully utilized. So, a load average of 4.00 on a 4-core CPU means all cores are fully utilized. When setting a threshold, consider your CPU's core count. For example, if you have 8 cores, a load of 2.00 might still be considered low. **Formula:** Threshold &lt; (Number of CPU Cores) ### The Auto-Suspend Script Let's create a script named auto-suspend.sh. ```bash #!/bin/bash # --- Configuration --- # Threshold for 5-minute load average. If load goes below this, we start counting. # Adjust based on your CPU cores. For example, if you have 8 cores, 1.0 or 2.0 might be 'low'. LOAD_THRESHOLD=0.5 # Time (in seconds) between each load check. CHECK_INTERVAL=30 # How many consecutive times must the load be below the threshold and other conditions met # before suspending. This prevents accidental suspend during momentary dips. CONSECUTIVE_CHECKS_REQUIRED=5 # Path to the log file. LOG_FILE="/var/log/auto_suspend.log" # Path to a file that, if it exists, will prevent the system from suspending. # This is useful for manual override (e.g., during large downloads/compilations). NO_SLEEP_FILE="/tmp/no_auto_suspend" # --- Functions --- # Function to log messages with a timestamp log() { echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE" } # Function to get the current 5-minute load average get_load_average() { # /proc/loadavg contains three numbers: 1-min, 5-min, 15-min load averages # We want the second number (5-minute average) awk '{print $2}' /proc/loadavg } # Function to check if the system is currently active (users logged in, X session active) is_system_active() { # Check for any active user sessions (local or SSH) # Exclude system users like 'reboot' or 'runlevel' if who | grep -v 'reboot' | grep -v 'runlevel' | grep -v 'LOGIN' | grep -q -v ' pts/0 ' ; then # 'pts/0' might be this script's own terminal log "Active users detected." return 0 # System is active fi # Check for active graphical sessions (Xorg processes or Wayland) if pgrep -x Xorg >/dev/null || pgrep -x gnome-shell >/dev/null || pgrep -x kwin_wayland >/dev/null; then log "Active graphical session detected." return 0 # System is active fi # Check for active logind sessions (more robust) if loginctl list-sessions --no-legend | awk '{print $1}' | while read -r session_id; do if loginctl show-session "$session_id" | grep -q "State=active"; then log "Active logind session detected (ID: $session_id)." return 0 # System is active fi done; then return 0 # System is active due to a logind session fi # Check for specific processes you might want to prevent sleep for (e.g., apt, rsync, backups) # Add more `pgrep` commands as needed if pgrep -x apt >/dev/null || pgrep -x rsync >/dev/null || pgrep -x borg >/dev/null; then log "Specific critical process (apt, rsync, borg) detected." return 0 # System is active fi # If no activity detected return 1 # System is NOT active } # Function to perform the suspend action perform_suspend() { log "Initiating system suspend..." # You need root privileges for this. # systemctl is the modern way. pm-suspend is older. # echo mem > /sys/power/state is low-level. systemctl suspend # This point is reached *after* the system resumes from suspend log "System resumed from suspend. Resuming monitoring." } # --- Main Logic --- log "Auto-suspend script started. PID: $$" log "Configuration: Load Threshold=${LOAD_THRESHOLD}, Check Interval=${CHECK_INTERVAL}s, Consecutive Checks=${CONSECutive_CHECKS_REQUIRED}" # Initialize counter for consecutive low-load checks low_load_count=0 while true; do # 1. Get current load average current_load=$(get_load_average) log "Current 5-min load average: $current_load" # 2. Check for manual override file if [ -f "$NO_SLEEP_FILE" ]; then log "Override file '$NO_SLEEP_FILE' found. Suspend prevented." low_load_count=0 # Reset count as we're intentionally not suspending sleep "$CHECK_INTERVAL" continue # Skip to next loop iteration fi # 3. Check if load is below threshold # Using 'bc -l' for floating point comparison if (( $(echo "$current_load < $LOAD_THRESHOLD" | bc -l) )); then # Load is low. Increment counter. low_load_count=$((low_load_count + 1)) log "Load is low ($current_load < $LOAD_THRESHOLD). Low load count: $low_load_count/$CONSECUTIVE_CHECKS_REQUIRED" # 4. Check if consecutive low-load conditions are met if [ "$low_load_count" -ge "$CONSECUTIVE_CHECKS_REQUIRED" ]; then # 5. Perform final activity check before suspending if is_system_active; then log "System became active during low-load period. Resetting low load count." low_load_count=0 # Reset because activity was detected else # All conditions met: load is low consistently, no active users, no override. log "All conditions met: Load consistently low, system inactive." perform_suspend # After suspend and resume, reset the count to prevent immediate re-suspend low_load_count=0 fi fi else # Load is NOT low. Reset the counter if it was accumulating. if [ "$low_load_count" -gt 0 ]; then log "Load is no longer low ($current_load >= $LOAD_THRESHOLD). Resetting low load count." low_load_count=0 else log "Load is high ($current_load >= $LOAD_THRESHOLD). Not accumulating." fi fi # Wait for the next check interval sleep "$CHECK_INTERVAL" done ``` IGNORE\_WHEN\_COPYING_START Use code [with caution](https://support.google.com/legal/answer/13505487). Bash IGNORE\_WHEN\_COPYING_END ### How to Set Up and Run the Script with Systemd Running this script directly in a terminal is not ideal. It needs to run continuously in the background, survive reboots, and have the necessary permissions. systemd is the best way to manage this on modern Linux systems. #### 1\. Save the Script Save the script above as /usr/local/bin/auto-suspend.sh. ```bash sudo nano /usr/local/bin/auto-suspend.sh # Paste the script content # Ctrl+X, Y, Enter to save and exit ``` #### 2\. Make the Script Executable ```bash sudo chmod +x /usr/local/bin/auto-suspend.sh ``` #### 3\. Create a Systemd Service Unit File Create a new file for the systemd service at /etc/systemd/system/auto-suspend.service. `sudo nano /etc/systemd/system/auto-suspend.service` Paste the following content: ```ini [Unit] Description=Automatic Suspend based on Load Average After=network.target multi-user.target graphical.target [Service] ExecStart=/usr/local/bin/auto-suspend.sh # User=root # Run as root to allow suspend, or use sudo in script (less secure) Type=simple # If the script exits for some reason, restart it Restart=on-failure RestartSec=5s StandardOutput=append:/var/log/auto_suspend.log StandardError=append:/var/log/auto_suspend.log [Install] WantedBy=multi-user.target graphical.target ``` **Explanation of Systemd Service File:** - **\[Unit\]**: - Description: A brief description of the service. - After: Specifies that this service should start after the network and multi-user environment are up. - **\[Service\]**: - ExecStart: The command to execute when the service starts. - User=root: **Important!** The systemctl suspend command requires root privileges. By default, systemd services run as root unless User= is specified. Make sure this service runs as root or a user with sudo privileges for systemctl suspend without a password. - Type=simple: The process defined in ExecStart is the main process. - Restart=on-failure: If the script exits with a non-zero status, systemd will try to restart it after RestartSec. - RestartSec=5s: Wait 5 seconds before attempting a restart. - StandardOutput/StandardError: Redirects stdout and stderr to the specified log file. This is useful for debugging. - **\[Install\]**: - WantedBy=multi-user.target graphical.target: Ensures that this service is started when the system boots into a multi-user environment (including graphical desktops). #### 4\. Reload Systemd, Enable, and Start the Service ``` sudo systemctl daemon-reload # Reload systemd manager configuration sudo systemctl enable auto-suspend.service # Enable the service to start on boot sudo systemctl start auto-suspend.service # Start the service immediately ``` #### 5\. Verify the Service Status Check if the service is running correctly: `sudo systemctl status auto-suspend.service` You should see output indicating it's active (running). #### 6\. Monitor the Logs Keep an eye on the log file to see the script's activity: `tail -f /var/log/auto_suspend.log` ### How to Manually Override / Prevent Sleep To temporarily prevent the system from sleeping, even if the load is low, you can create the NO\_SLEEP\_FILE defined in the script: `sudo touch /tmp/no_auto_suspend` To allow the system to sleep again, remove the file: `sudo rm /tmp/no_auto_suspend` ### Important Considerations and Troubleshooting - **Permissions:** Ensure /usr/local/bin/auto-suspend.sh is executable (chmod +x). The systemd service usually runs as root, which is necessary for systemctl suspend. - **Load Threshold:** Tune LOAD_THRESHOLD based on your CPU (number of cores) and what you consider "idle." A load of 0.5 on an 8-core CPU is very different from 0.5 on a single-core CPU. - **CONSECUTIVE\_CHECKS\_REQUIRED:** This is crucial. A higher number makes the suspend decision more robust against transient dips in load, but it means it will take longer to suspend once conditions are met. - **Activity Checks (is\_system\_active function):** This is the most complex part to get right. You might need to add more checks specific to your use case (e.g., checking for specific background processes like downloads, backups, media playback, or active ssh sessions with specific commands running). The current implementation attempts to cover common scenarios. - **System Suspend (S3):** Ensure your system's BIOS/UEFI is configured to support S3 (Suspend-to-RAM) if you encounter issues. - **Wake-up Source:** Once suspended, you'll need a way to wake the system up (e.g., power button, keyboard/mouse activity, Wake-on-LAN if enabled). - **Hibernation (Suspend-to-Disk):** If you prefer hibernation (saving state to disk and powering off), change systemctl suspend to systemctl hibernate. This typically requires a swap partition or swap file at least as large as your RAM. - **Debugging:** Use journalctl -u auto-suspend.service -f in addition to tail -f /var/log/auto_suspend.log to see systemd's perspective and any errors if the script itself fails to run. This setup provides a robust and customizable solution for automatically suspending your Linux system based on its load average and activity.