In this article I will explain a trick to run functions on a custom interval. Maybe you need to run a script function every 2 hours, 3 hours, 8 hours, you name it.
This will be done with the help of campaign labels. You can use labels to store and modify any value, like a variable. If you don’t know what campaign labels are, check out this from Google.
Function gethours
function gethours(labelname){
var currentDate = new Date();
var labelapp = labelname+currentDate.toISOString();
if(AdsApp.labels().withCondition("label.name REGEXP_MATCH '.*" + labelname +".*'").get().hasNext()){
var labelIterator = AdsApp.labels().withCondition("label.name REGEXP_MATCH '.*" + labelname +".*'").get();
while(labelIterator.hasNext()){
var thisLabel = labelIterator.next();
var thisLabelName = thisLabel.getName();
//Logger.log(thisLabelName);
var time = thisLabelName.replace(labelname,"");
var elapsedTime = (currentDate - new Date(time)) / (1000 * 60 * 60);
}
}
if(!AdsApp.labels().withCondition("label.name REGEXP_MATCH '.*" + labelname +".*'").get().hasNext()){
AdsApp.createLabel(labelapp);
var elapsedTime = 1000;
}
return elapsedTime;
}
Function Overview
The `gethours` function takes a `labelname` parameter and calculates the elapsed time in hours since a label with that name was created in the Google Ads account. If no label with the given name exists, it creates a new label.
Key Concepts Used
Date object:
The `Date` object in JavaScript represents a specific moment in time. It provides methods to work with dates and times.
Label creation and retrieval:
The function uses the `AdsApp.labels()` method to retrieve labels from the Google Ads account and the `AdsApp.createLabel()` method to create a new label.
Regular expression matching:
The function uses a regular expression pattern `’.*’ + labelname +’.*’` to match labels with names containing the provided `labelname`.
Time calculation:
The function calculates the elapsed time by subtracting the timestamp of the label from the current date and converting the result from milliseconds to hours. hope this explanation helps you understand the functionality of the `gethours` function in the Google Ads script. Let me know if you have an questions in the comments!
Example use case Google Ads Script
Send Campaign Spend Report in email every 6 hours
function main() {
// Get the elapsed hours since the last execution
var hoursElapsed = gethours("campaignSpendEmail_");
// Check if 6 or more hours have passed
if (hoursElapsed >= 6) {
Logger.log("Generating campaign spend report...");
// Initialize an array to hold campaign spend data
var campaignData = [];
// Retrieve all enabled campaigns
var campaigns = AdsApp.campaigns()
.withCondition("Status = ENABLED")
.get();
// Iterate through campaigns and collect spend data
while (campaigns.hasNext()) {
var campaign = campaigns.next();
var campaignName = campaign.getName();
var cost = campaign.getStatsFor("TODAY").getCost(); // Get today's spend
// Format cost to two decimal places
var costFormatted = cost.toFixed(2);
// Add campaign data to the array
campaignData.push({
name: campaignName,
cost: costFormatted,
});
}
// Create the email body
var emailBody = "Campaign Spend Report:\n\n";
campaignData.forEach(function (item) {
emailBody += "Campaign: " + item.name + "\n";
emailBody += "Spend Today: $" + item.cost + "\n\n";
});
// Send the email
MailApp.sendEmail({
to: "your-email@example.com",
subject: "Campaign Spend Report",
body: emailBody,
});
Logger.log("Campaign spend report email sent.");
} else {
Logger.log(
"Only " +
hoursElapsed.toFixed(2) +
" hours since last email. Skipping."
);
}
}
function gethours(labelname){
var currentDate = new Date();
var labelapp = labelname+currentDate.toISOString();
if(AdsApp.labels().withCondition("label.name REGEXP_MATCH '.*" + labelname +".*'").get().hasNext()){
var labelIterator = AdsApp.labels().withCondition("label.name REGEXP_MATCH '.*" + labelname +".*'").get();
while(labelIterator.hasNext()){
var thisLabel = labelIterator.next();
var thisLabelName = thisLabel.getName();
//Logger.log(thisLabelName);
var time = thisLabelName.replace(labelname,"");
var elapsedTime = (currentDate - new Date(time)) / (1000 * 60 * 60);
}
}
if(!AdsApp.labels().withCondition("label.name REGEXP_MATCH '.*" + labelname +".*'").get().hasNext()){
AdsApp.createLabel(labelapp);
var elapsedTime = 1000;
}
return elapsedTime;
}
Explanation
Main Function
main()
: This is the entry point of the script.hoursElapsed
: Callsgethours("campaignSpendEmail_")
to determine how many hours have passed since the last email was sent.- Condition: If
hoursElapsed
is 6 or more, the script proceeds to generate and send the email. - Campaign Retrieval:
- Retrieves all campaigns that are currently enabled.
- Iterates through each campaign to collect the campaign name and today’s spend.
- Data Collection:
- Stores the campaign name and spend in an array
campaignData
.
- Stores the campaign name and spend in an array
- Email Creation:
- Builds the email body by looping through
campaignData
and appending each campaign’s information.
- Builds the email body by looping through
- Email Sending:
- Uses
MailApp.sendEmail()
to send the email to the specified email address.
- Uses
- Logging:
- Outputs messages to the console to track the script’s execution.
gethours
Function
- Purpose: Calculates the elapsed time since the last time the script ran.
- Label Retrieval:
- Searches for any label that starts with the provided
labelname
.
- Searches for any label that starts with the provided
- Elapsed Time Calculation:
- If a label is found, calculates the time difference between the current date and the date stored in the label’s name.
- Converts the elapsed time from milliseconds to hours.
- Label Management:
- Removes the old label.
- Creates a new label with the current timestamp.
- Return Value: Returns the elapsed time in hours.
How to Use This Script
- Update the Email Address:
- Replace
"your.email@example.com"
with the email address where you want to receive the campaign spend report.
- Replace
- Authorize Necessary Services:
- The script uses
MailApp
, so make sure you authorize the script to send emails on your behalf.
- The script uses
- Scheduling the Script:
- Set up the script to run hourly:
- In the Google Ads script interface, after adding your script, click on the “Create schedule” button.
- Set the script to run hourly.
- The
gethours
function will ensure that the email is only sent every 6 hours.
- Set up the script to run hourly:
Final Thoughts
This script provides an automated way to stay informed about your campaign spending by receiving regular emails every six hours. By adjusting the parameters and customizing the code, you can tailor the script to meet your specific needs.
Conclusion
In conclusion, leveraging the gethours
function with campaign labels in Google Ads scripts offers a powerful and flexible solution for executing functions at custom intervals. This method enables you to automate routine tasks—such as adjusting bids, pausing high-spend campaigns, or sending performance reports—based on precise timing without relying on external schedulers or complex setups.
By embedding timestamps within labels, you can effectively track when a function last ran and calculate the elapsed time.
This approach not only streamlines your workflow but also enhances the responsiveness of your campaigns to real-time data, ensuring that adjustments are made promptly and efficiently.
Now is the perfect time to integrate this technique into your own Google Ads management strategy.
Begin by identifying tasks that would benefit from regular automation at specific intervals.
Implement the gethours
function in your scripts to control the timing of these tasks precisely.
If you need any custom Google Ads script solution mail me at hello@lucianionescu.com
Happy Scripting🤘