The Google Apps Script will activate only on weekdays between the hours of 10 AM and 5 PM, running every hour

function Purchase() {
  var ss=SpreadsheetApp.getActive();
  var sheet=ss.getSheetByName("Buy");  
  var Cvalues=sheet.getRange(2,3,sheet.getLastRow()-1,1).getValues();
  var Avalues=sheet.getRange(2,1,sheet.getLastRow()-1,1).getValues();
  var results=[];

for(var i=0;i<Cvalues.length;i++){

if(Cvalues[i][0]<=-3){
      results.push(" "+ Avalues[i]);
      results.push("Price "+ Cvalues[i]);
      MailApp.sendEmail('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6d08000c040a11141357171b1318961e1018">[email protected]</a>', 'Purchase Alert',results.join("\n")); 
    }
  }

}

What additional code needs to be added to run this function during weekdays business hours between 10 AM and 5 PM every hour?

Answer №1

Instead of constantly checking the day and hour manually, why not create a helper function that can automatically trigger a Buy() action during specific hours on weekdays? This way, your script will only execute when necessary:

function checkAndBuy() {
    var currentDay = Utilities.formatDate(new Date(),"GMT-4","EEEE");
    var currentHour = parseInt(Utilities.formatDate(new Date(), "GMT-4", "HH"));
    
    if(currentDay.match(/Monday|Tuesday|Wednesday|Thursday|Friday/) && currentHour >= 10 && currentHour < 17) {
        Buy();
    }
}

https://example.com/image.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

http-proxy-middleware - serving static content

I am currently working on integrating my static landing page with an express.js app (using react.js for the single page application). For my landing page, I have set up a proxy using http-proxy-middleware. Here is what my server.js file for the static pag ...

Create a React component using the value stored within an object

I am interested in creating an object: import React from "react"; import { Registration } from "../../"; const RouteObj = { Registration: { route: "/registration", comp: <Registration /> } }; export default RouteObj; Next, in a separat ...

What is the best way to cancel a Promise if it hasn't been resolved yet

Let's consider a situation where I have implemented a search function to make an HTTP call. Each call made can have varying durations, and it is crucial for the system to cancel any previous HTTP requests and only await results from the latest call. ...

Sorting through various data inputs in one JSON file

I have a JSON file containing an array of objects: obj= [{fname:"abhi",age:5,class:"ten",lanme:"kumar" },{fname:"abhi",age:5,class:"ten",lanme:"kumar" },{fname:"abhi",age:5,class:"t ...

Getting a specific value from a REST API array in JavaScript: Tips and tricks

After being stuck on this problem for 8 hours, I finally decided to seek help: In my JavaScript file, I am attempting to extract data from a REST API response. The response consists of an array of objects structured like this: [{"start":"2017-04-21 14:40 ...

What prevents certain scenarios from being encapsulated within a try/catch block?

Just attempted to handle ENOENT by using a naive approach like this: try { res.sendFile(path); } catch (e) { if (e.code === 'ENOENT') { res.send('placeholder'); } else { throw e; } } Unfortunately, this method is ineffectiv ...

Storing approximately 1 kilobyte of information throughout various pages

Is it feasible to store approximately 1kb of data while transitioning between two pages on the same domain using Javascript, Jquery (1.7), and Ajax? For instance, a user inputs data into a textbox on one page and then moves to another specific page. Can ...

What is the method for invoking a function with arguments within an HTML `<p>` element?

I am looking to display like and dislike percentages on cards. <v-card v-if="software[2] == searched || searched == ''" class="software-card" > <h3>{{ software[2] }}</h3> ...

What is the best way to conceal the header on a 404 error page?

<HeaderContainer> <Switch> <Route exact path='/counters' component={ParentCounterContainer}/> <Route exact path='/about' component={AboutContainer} /> <Route exact path='/' component={H ...

Tips for eliminating nested switchMaps with early returns

In my project, I have implemented 3 different endpoints that return upcoming, current, and past events. The requirement is to display only the event that is the farthest in the future without making unnecessary calls to all endpoints at once. To achieve th ...

Take away the dropdown selection once the form has been submitted

Every day, a user fills out a form ten times. They choose an option from the dropdown menu, fill out the form, and submit it. I am looking for a solution to either remove the selected option once it's been submitted or mark it as complete by highlight ...

The calculator is malfunctioning and unable to perform calculations

export default function App() { const [activeKey, setActiveKey] = useState(0); const [storeArr, setStoreArr] = useState([]); function click(selector) { setActiveKey(selector); if (activeKey !== "=") { setStoreArr([...storeArr ...

What is the best way to access and display the innerText of elements that have been removed using console

When I call the updateCartTotal() function, my goal is to display in the console the items that have been removed from the shopping cart. Every time I click on the remove button, I want it to show the item and the price. However, instead of displaying the ...

When organizing data, the key value pair automatically sorts information according to the specified key

I have created a key value pair in Angular. The key represents the questionId and the value is the baseQuestion. The baseQuestion value may be null. One issue I am facing is that after insertion, the key value pairs are automatically sorted in ascending ...

Ensure the presence of an editable column within a table using a jQuery function

Within the table, the first column is editable. Upon making a change to it, I want an alert to appear indicating that a change has occurred. The check function is being called after a delay of 5000ms. Embedding Code Snippet for Reference I suspect there ...

The error message "TypeError: Cannot set property 'href' of undefined" occurred at angular.js line 12520 when trying to set $window.location.href

Has anyone tried using a directive function to redirect when clicking with ng-click? Here is the HTML code: <a ng-click="navbarlinksCtrl.clickedfr()" ng-class="{active: clickedfr()}">FR</a><br> <a ng-click="navbarlinksCtrl.clickeden( ...

Tips for inserting user input into an array and showcasing it

const [inputValue, setInputValue] = useState(""); return ( <input onChange={(event) => setInputValue(event.target.value)} /> <p>{inputValue}</p> ); I'm facing a problem where I need to take input from a user and store it in ...

Uncover and control nested objects in JSON data

Having a dynamic foo object with the possibility of nested parent objects raises the question of how to effectively: 1) Determine the last object that has a parent? 2) Create an array containing all nested parent objects along with the initial obj (foo.o ...

Troubleshooting: Node.js Express Server GET Handler Failing to Function

Recently, I've been attempting to build a GET request handler in Express.js. Here's the snippet of code I've put together: // include necessary files and packages const express = require('./data.json'); var app = express(); var m ...

Sorting a parent array in AngularJS using a child array's Date field as the basis

I have an array of arrays of objects with the following structure: parentArray = [ [{id:1, date:1505020200000}, {id:4, date:1505020200000 }], [{id:2, date:1504681500000}], [{id:3, date:1504671000000}, {id:20, date:1504671000000}] ] Each nested array cont ...