Skip to content

Instantly share code, notes, and snippets.

@nicka101
Last active February 8, 2024 12:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save nicka101/f1001edd13852dd957ef6221ecccd5f7 to your computer and use it in GitHub Desktop.
Save nicka101/f1001edd13852dd957ef6221ecccd5f7 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