林博仁 Buo-ren Lin
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # 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.

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Google Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully