Skip to content

Instantly share code, notes, and snippets.

@wechain
Forked from nicka101/check_spare_cpu.sh
Created September 19, 2021 10:16
Show Gist options
  • Save wechain/ab12b158014e3409755dee7614edf6ec to your computer and use it in GitHub Desktop.
Save wechain/ab12b158014e3409755dee7614edf6ec to your computer and use it in GitHub Desktop.
Xmrig (with idle mining) via systemd and screen
#!/bin/bash
# Check the amount of CPU being consumed by processes other than xmrig
# Takes a single (optional) argument, the name of the screen to target. Defaults to "xmrig" if unspecified
set -e
#12.5% or 2 full cores (with our 16 total)
IDLE_THRESHOLD=12.5
TARGET_SCREEN="${1:-xmrig}"
NUM_CORES=$(cat /proc/cpuinfo | grep "core id" | wc -l)
LAST_STATE=0
while true; do
NON_XMRIG_CPU=$(ps -eo "%C|%a" --no-header | awk -F '|' 'BEGIN { total = 0 }; index($2, "xmrig") == 0 { total += $1 }; END { print total }')
TOTAL_NON_XMRIG_CPU=$(echo "scale=2; $NON_XMRIG_CPU / $NUM_CORES" | bc)
CURRENT_STATE=$(echo "$TOTAL_NON_XMRIG_CPU > $IDLE_THRESHOLD" | bc)
if (( $CURRENT_STATE && !$LAST_STATE )); then
#System is too active, pause the miner
screen -p 0 -S $TARGET_SCREEN -X eval 'stuff "p"\\015'
echo "Miner pause"
elif (( !$CURRENT_STATE && $LAST_STATE )); then
#System is idle again, resume
screen -p 0 -S $TARGET_SCREEN -X eval 'stuff "r"\\015'
echo "Miner resume"
fi
LAST_STATE=$CURRENT_STATE
sleep 1
done
[Unit]
Description=Idle mining for XMRig - %i
Requires=xmrig@%i
[Service]
Type=simple
WorkingDirectory=/var/xmrig
User=root
RestartSec=10
Restart=always
ExecStart=/usr/local/bin/check_spare_cpu xmrig-%i
[Install]
WantedBy=network-online.target
[Unit]
Description=XMRig Miner - %i
[Service]
Type=simple
WorkingDirectory=/var/xmrig
User=root
RestartSec=30
Restart=on-failure
ExecStart=/usr/bin/screen -DmS xmrig-%i ./xmrig -c %i.json
[Install]
WantedBy=network-online.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment