Skip to content

Instantly share code, notes, and snippets.

@onlime
Created January 6, 2023 10:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save onlime/8d1022a21b88c7c0ef3baae70d37f901 to your computer and use it in GitHub Desktop.
Save onlime/8d1022a21b88c7c0ef3baae70d37f901 to your computer and use it in GitHub Desktop.
MySQL process killer for long running Sleep processes
#!/bin/bash
# Number of seconds a query is allowed to execute before it is killed. (default: 3h)
MAX_EXEC_TIME=${1:-10800}
MYSQL_USER=your-mysql-user
mysql -sNB -e "SHOW FULL PROCESSLIST" \
| sed 's/\t/ /g' \
| sed 's/ \+/ /g' \
| while read process_id user host db command_type time state info time_ms rows_sent rows_examined; do
if (( $time > $MAX_EXEC_TIME )); then
if [ "$command_type" == "Sleep" ] && [ "$user" == "$MYSQL_USER" ]; then
echo "$user - killing thread because sleeping for $time seconds: KILL $process_id"
# echo "dry-run. Please run 'KILL $process_id' (or 'mysqladmin kill $process_id') manually!"
# mysql -e "KILL $process_id"
mysqladmin kill $process_id
fi
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment