Skip to content

Instantly share code, notes, and snippets.

@bayucandra
Created December 25, 2024 09:08
Show Gist options
  • Save bayucandra/abd654109d176d6ad49f26de4a67cc5e to your computer and use it in GitHub Desktop.
Save bayucandra/abd654109d176d6ad49f26de4a67cc5e to your computer and use it in GitHub Desktop.
Start VM instance when start to work. It will auto stop when computer is idle for certain amount of time as defined on the config vars
#!/bin/bash
# Config Vars
MAX_IDLE_TIME_MINUTES=15
GCP_COMPUTE_NAME=ml-node
GCP_COMPUTE_ZONE=us-central1-c
GCP_COMPUTE_IS_STOPPED=0
egress() {
echo "Exiting script...."
if [ $GCP_COMPUTE_IS_STOPPED -ne 1 ]; then
gcloud compute instances stop ${GCP_COMPUTE_NAME} --zone ${GCP_COMPUTE_ZONE}
fi
}
trap egress EXIT
# trap egress SIGINT SIGTERM SIGTSTP
gcloud compute instances start ${GCP_COMPUTE_NAME} --zone ${GCP_COMPUTE_ZONE}
while true; do
CUR_IDLE_TIME_MINUTES=$((`xprintidle`/1000/60))
echo -ne "Current idle time: ${CUR_IDLE_TIME_MINUTES} Minutes ........ "\\r
if [ $CUR_IDLE_TIME_MINUTES -ge $MAX_IDLE_TIME_MINUTES ]; then
echo "Stopping*****"
gcloud compute instances stop ${GCP_COMPUTE_NAME} --zone ${GCP_COMPUTE_ZONE}
GCP_COMPUTE_IS_STOPPED=1
break
fi
sleep 1
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment