Purchase a Google Cloud account: Use Cloud Scheduler in conjunction with Cloud Functions to automatically switch virtual machines on a scheduled basis.
In day-to-day cloud operations, many teams encounter a painful “budget black hole”:
The server is idle.
For example, the company’s development and testing environments, as well as internal reporting systems, are typically used only during the 8 to 10 hours of daytime working hours. However, because operations staff are too lazy to bother with maintenance, or often forget to shut down the servers after work, these machines frequently run 24/7—365 days a year—in the background, consuming power while idling.
In Google Cloud (GCP)’s billing model, virtual machines (Compute Engine) are billed by the second and based on instance specifications. This means,
If you leave your server running after work, the wasted server costs for an entire night could easily account for more than 60% of your monthly bill.
.
The traditional approach is to write a complex Shell script, paired with local…
cron
Scheduled task. However, once the local machine loses its network connection or power, the script will fail to execute.
Within Google Cloud’s modern ecosystem, there exists an exceptionally elegant serverless golden duo:
Use Cloud Scheduler in conjunction with Cloud Functions.
. It’s like a fully automated “cloud‑based switchgear”: you simply speak up and write a few lines of a scheduling script, and Google will handle the timed on‑off operations for your servers at sub‑second speeds—without consuming any server resources in the process.
Today, we’re ditching all the usual official jargon and diving straight into real‑world practice, guiding you step by step to build an iron‑clad, enterprise‑grade timed‑discount defense.
Phase 1: In-depth Decomposition – The “Three-Dimensional World Model” of Cloud-Based Scheduled On/Off Control
Before you start writing code, you must first establish a mental model of the physical architecture for this automated operations workflow. The entire production line is seamlessly integrated from three core components:
Cloud Scheduler: A fully managed timer service (equivalent to a cloud-based crontab). You use standard Linux Cron syntax to tell it: “Wake me up at 9 a.m. every day, and wake me up at 8 p.m. every day.” It transmits a signal on time, at the scheduled moment.
Secret Messenger (Pub/Sub Message Queue): A secure intranet radio station. After the alarm goes off, it packages and sends a simple command—such as “start” or “stop”—to a specific channel on the radio.
Electrical Engineering Robot (Cloud Functions): Google’s lightweight serverless functions. It normally remains in a state of complete dormancy (at zero cost). As soon as it receives the corresponding command over the radio, it instantly “raises the dead” in the background within 0.5 seconds, invokes Google Cloud’s API to power on or off the target virtual machine with a single click, and then proceeds to physically destroy itself on the spot.
Phase Two: The Eve of Deployment—Securing Legal Identity for the Robot (IAM)
In letting Cloud Functi
Before deploying the on‑premises server, we must rigorously adhere to the principle of least privilege, granting it a properly authorized privileged access credential to prevent excessive permissions from inadvertently compromising other critical assets.
Log in to the GCP Console and navigate to “IAM & Admin”> “Service Accounts.”
Click “Create service account” and name it vm-timer-executor.
Precision provisioning for the smallest role: On the role assignment page, search for and select “Compute Instance Admin (v1)”. Note: For stricter security, you can create a custom role that includes only the `compute.instances.start` and `compute.instances.stop` permissions.
Click Finish.
Phase 3: Hands-on Exercise 1 – Writing the Core Toggle Code for Cloud Functions
We have arrived at the core computing battlefield. We need to write a minimal Node.js script that can recognize a secret code and issue commands to the server.
Search for and navigate to the Cloud Functions page, then click “Create Function.”
Basic Settings: Function Name: vm-auto-switcher. Region: Select the region closest to your virtual machine (e.g., asia-east1 – Taiwan). Trigger Type: Select “Cloud Pub/Sub” from the drop-down menu. Click “Create New Topic” and name it “vm-timer-topic.”
Runtime parameter adjustment: Expand the “Runtime, Build, Link, and Security Settings” section below. In the Service Account field, you must disable the default account and precisely select the vm-timer-executor service account that we created in the second phase.
Click Next to enter the code editor. Runtime Environment Selection
Node.js 20
(Or any language you’re familiar with).
to put
index.js
Clear all the code in there and paste the following robust control code that meets large‑enterprise production‑environment standards:
JavaScript
const Compute = require('@google-cloud/compute');
const compute = new Compute();
exports.manageVmStatus = async (cloudEvent) => {
// 1. Forcefully unwrap the encrypted radio signal received from the Pub/Sub broadcaster
const base64Data = cloudEvent.data.message.data;
const jsonS
string = Buffer.from(base64Data, 'base64').toString();
const payload = JSON.parse(jsonString);
// 2. Precisely extract the design drawings: Which machine in which area do you intend to modify? What function do you want it to perform?
const { zone, instanceName, action } = payload;
if (! zone || ! instanceName || ! action) {
console.error('【Critical Error】Missing parameters! Must include zone, instanceName, and action!');
return;
}
const zoneObj = compute.zone(zone);
const vm = zoneObj.vm(instanceName);
console.log('【Automated O&M Activation】Attempting to perform the [${action}] operation on the virtual machine [${instanceName}] located in ${zone}...');
try {
if (action.toLowerCase() === 'start') {
// Execute one-click power-on
await vm.start();
console.log('【Success】The power-on command has been successfully issued to the virtual machine [${instanceName}]; it is now being fully awakened!');
} else if (action.toLowerCase() === 'stop') {
// Perform a one-click secure shutdown
await vm.stop();
console.log('【Success】Shutdown command successfully issued to virtual machine [${instanceName}]; initiating safe power-off!');
} else {
console.warn('【Warning】Unrecognized operation command: ${action}. This function only supports start or stop.');
}
} catch (error) {
console.error('【Physics Failure】An error occurred during execution: ${error.message}');
}
};
Casually picked up the one next to it.
package.json
Modified to include Google’s official
Dependencies of the Compute library:
JSON
{
"dependencies": {
"@google-cloud/compute": "^4.0.0",
"@google-cloud/cloudevents-conformance": "^0.2.2"
}
}
Change the “Function to be executed (Entry point)” in the upper-right corner to:
manageVmStatus
. Click
“Deploy”
.
Phase 4: Practical Exercise II – Configuring Cloud Scheduler to Hardcode a Scheduled Trigger
Once the function is deployed, it’s like a secret agent quietly waiting for its signal. Now, we’re going to set up two cloud-based timers: one to wake it up in the morning and another to send it to sleep at night.
Search to enter
Cloud Scheduler (Cloud Scheduled Tasks)
Page.
1. Alarm 1: Set to power on at full speed from Monday to Friday at 8:30 a.m.
Click
Create job
:
Name: cron-start-dev-vm.
Frequency: Enter a standard Linux Cron expression: 30 8 * * 1-5. (Translation: Triggers every Monday through Friday at 8:30 a.m.)
Time Zone: Select your local primary time zone (e.g., Shanghai, China).
Target type: Select Pub/Sub.
Topic: Select the vm-timer-topic we just created.
Message body: This is the core payload injected into the robot, precisely formatted as the following JSON command: JSON{ "zone": "asia-east1-a", "instanceName": "my-dev-workstation", "action": "start"}
Click Create.
2. Alarm 2: Set to force a shutdown at 8:30 PM from Monday to Friday.
Click Create Job again:
Name: cron-stop-dev-vm.
Frequency: Enter 30 20 * * 1-5. (Translation: Triggers every Monday through Friday at 8:30 PM.)
Target type: Pub/Sub, with the topic remaining vm-timer-topic.
Message body: Change the action to a shutdown command: JSON{ "zone": "asia-east1-a", "instanceName": "my-dev-workst"}
action", "action": "stop"}
Click Create. At this point, the fully automated, self-closing looped barbed-wire fence has been completely locked shut.
Phase Five: The Scene Where Miracles Are Witnessed—“Hands-On Compression” Manual Testing Exercise
Configuration is complete—do we really have to sit around idly until 8:30 p.m. to see whether it takes effect? DevOps teams at major companies never leave things to chance; we’ll run an “artificial catalysis test” right on site.
Make sure that your virtual machine named my-dev-workstation is currently in the Running state.
You have arrived at the Cloud Scheduler list page.
Locate the cron-stop-dev-vm job responsible for shutting down the VM, click the three-dot menu on its right, and select “Force run” without hesitation.
At the moment of the click, Cloud Scheduler will forcibly bypass the time constraint and inject a shutdown signal into Pub/Sub.
At this moment, you immediately switch back to
Compute Engine virtual machine list
. You will miraculously find that the server, which had previously been showing a green status indicator, has instantly turned yellow—without any manual intervention.
Stopping
,After a few seconds, it completely turns gray and enters
Terminated
(Power off) Hibernation state.
The function to go to
Logs (Log)
Take a look at the large screen—the code traces we just wrote are clearly visible:
[Success] The shutdown command has been successfully issued to the virtual machine [my-dev-workstation]. Initiating safe power-off!
.
Mission accomplished! From now on, this machine will behave like a disciplined worker, clocking in and booting up at the appointed time, and shutting down automatically when it’s time to rest.
Phase 6: A Painful, Lessons-Learned Journey Avoiding Pitfalls in Production-Grade Automated Operations
This serverless architecture is incredibly smooth to use, and the cost‑saving benefits are immediate. However, to ensure stable operation in a true enterprise-scale production environment, as the chief architect, you must immediately reinforce the solution’s boundaries and guard against the following two hidden pitfalls:
1. The fatal “local disk data vanishes without a trace” risk (a unique pitfall specific to GCP)
Many beginners, in their quest for faster read/write speeds when running virtual machines, end up mounting…
Local SSD
Alternatively, configure the system to use an unsustainable non-persistent disk.
Disaster scenario: According to GCP’s underlying design, if you call `vm.stop()` to perform a physical shutdown, all data stored on the Local SSDs attached to that instance will be permanently erased by Google from the physical hardware the instant power is lost. Only data mounted to standard Persistent Disks can be preserved after shutdown.
Architectural Anti-Pitfall Guideline: For any server that is to be added to the scheduled power‑on/off queue, it is strictly prohibited to store any on‑premises data without multi‑site redundancy.
al SSD temporary core data. Make sure to take Persistent Disk assets across the board.
2. Beware of the wailing of "late-night overtime dogs" (humanized fusing mechanism)
Automation is too hard-core and sometimes brings negative feedback. For example, at 8: 30 p. m. on a Friday, the whole group of developers were frantically correcting bugs in the server in order to catch up with an emergency project. as a result, at 8: 30 p. m., Cloud Scheduler was extremely dedicated and ruthless to switch off the server with one click, resulting in the direct disconnection and packet loss of half of the code written by the development, and the whole group's direct mentality collapsed.
Hard core humanization tuning: don't blindly issue vm.stop() directly in the code.
Advanced solution: Before the shutdown code is executed, let the function perform one step of internal detection (such as checking the CPU usage of the current server or the number of network intranet connections through SSH or monitoring indicators).
If it is found that the CPU utilization rate is still greater than 20% (indicating that someone is under pressure or working overtime), the function will automatically send a flying book/DingTalk notice: "if signs of overtime are detected, the shutdown at night will be automatically skipped, and the check will be repeated after one hour's delay". The code has a line of warmth, which is the highest accomplishment of a mature operation and maintenance architect.
Summary
Using GCP Cloud Scheduler to cooperate with Cloud Functions to play with regular automatic virtual machine switching, the core industrial essence actually lies in 16 words:
Regular orders, wireless delivery, function orders, warmth fuse
.
You have completely bid farewell to the original state of physical targeting and using your mobile phone to connect VPN to manually shut down the server after work. With completely free Serverless computing power, go and buckle every cloud coin that shouldn't be wasted. Let the machine manage the machine, which is the most authentic and elegant money-saving posture in the modern cloud native era.
