Can't Add More Than One New Trigger to Script Function - google-apps-script

I am trying to make both of these new triggers a part of my existing function. I at one time got one to work, and when I added the second, both triggers would not be created at the same time. Help please.
// Trigger every 15 Minutes
ScriptApp.newTrigger('copyPriceData')
.timeBased()
.everyMinutes(2)
.create();
//Delete Trigger after Market Closes
ScriptApp.newTrigger("delete_Triggers")
.timeBased()
.after(6 * 60 * 1000)
.create();
Existing code is:
function CopyLive1() {
var date = new Date();
var day = date.getDay();
var hrs = date.getHours();
var min = date.getMinutes();
if ((hrs >= 15) && (hrs <= 15) && (min >= 46) && (min <= 46)) {
var sheet = SpreadsheetApp.getActiveSheet();
// Get more recent closing prices
var closePriceRange = sheet.getRange("F4");
var prevClosePriceRange = sheet.getRange("F5");
var closePrice = closePriceRange.getValue();
var prevClosePrice = prevClosePriceRange.getValue();
// Check if price data has updated. If so create new row and copy price data.
if (closePrice != prevClosePrice)
{sheet.insertRowsAfter(4, 1);
var rangeToCopy = sheet.getRange("B4:G4");
rangeToCopy.copyTo(sheet.getRange("B5:G5"), {contentsOnly:true});
}
sheet.deleteRow(1825);
}
}

Related

Change the value of a cell if another cell has a date that falls within the current week - apps script

In google sheets I have a task table. Included in the table is a column that has a timeline dropdown and a column that includes a do date. I am trying to change the value of the timeline column if the do date falls within the current week.
For example, using my screenshot below:
Today is 2/7/2023 - I would like to see if the do date falls within this current week (2/5/2023-2/11/2023). Because the do date falls within this week (2/10/2023) I would like the Timeline to change to "This Week"
Here is the code I have tried. I was thinking I could get the first day and last day of the current week, and then compare those two dates to the date listed in the do date column.
function onEdit(event){
var colK = 11; // Column Number of "K"
var changedRange = event.source.getActiveRange();
if (changedRange.getColumn() == colK) {
// An edit has occurred in Column K
//Get this week
var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
var last = first + 6; // last day is the first day + 6
var firstday = new Date(curr.setDate(first)).toUTCString();
var lastday = new Date(curr.setDate(last)).toUTCString();
var doDateTW = new Date(changedRange.getValue.setDate()).toUTCString();
//Set value to dropdown
var group = event.source.getActiveSheet().getRange(changedRange.getRow(), colK - 5);
if (doDateTW >= firstday && doDateTW <= lastday) {
group.setValue("This Week");
}
}
}
In your situation, how about the following modification?
Modified script:
function onEdit(event) {
var { range, source } = event;
var colK = 11;
var changedRange = source.getActiveRange();
if (changedRange.getColumn() == colK) {
var curr = new Date();
var year = curr.getFullYear();
var month = curr.getMonth();
var first = curr.getDate() - curr.getDay();
var last = first + 6;
var firstday = new Date(year, month, first).getTime();
var lastday = new Date(year, month, last).getTime();
var doDateTW = range.getValue().getTime();
var group = source.getActiveSheet().getRange(changedRange.getRow(), colK - 5);
if (doDateTW >= firstday && doDateTW <= lastday) {
group.setValue("This Week");
} else {
group.setValue(null);
}
}
}
When you put a date value to the column "K", when the inputted date value is in this week, "This Week" is put into column "F". When the inputted date value is not in this week, the cell of column "F" is cleared.
In this modification, I used your script of var first = curr.getDate() - curr.getDay(); and var last = first + 6;.

Error in Date Differences in Google Sheets App Script

In Googlesheets's "Sheet1", dates are manually entered in Column A.
When I enter a date in column A, Column B should be filled with the difference between new Date() and the date just entered in Column A.
Until now, I have tried the following code:
function onEdit() {
var s2=SpreadsheetApp.getActive().getSheetByName("Sheet1");
var lastRow=s2.getLastRow();
var entry_date =s2.getRange(lastRow, 1).getValue();
var now = new Date();
var diff = now-entry_date;
s2.getRange(lastRow, 2).setValue(diff);
}
However, Column B is giving very random results and I am not being able to understand. I just need the date difference to be filled in column B in the same row.
The result is looking odd to you because you are expecting it in days (the way the sheet would show it) but the script is showing you the result in milliseconds. To get the answer in number-of-days, try this:
function onEdit() {
var s2 = SpreadsheetApp.getActive().getSheetByName("Sheet1");
var lastRow = s2.getLastRow();
var entry_date = s2.getRange(lastRow, 1).getValue();
var now = new Date();
var diff = (now-entry_date) / (24 * 60 * 60 * 1000); // Divide by number of milliseconds in a day
s2.getRange(lastRow, 2).setValue(diff);
}
This will give you an output that looks like 3.4567 (days + fraction of day in milliseconds).
To get it rounded down to just the number of days, you could try this:
function onEdit() {
var s2 = SpreadsheetApp.getActive().getSheetByName("Sheet1");
var lastRow = s2.getLastRow();
var entry_date = s2.getRange(lastRow, 1).getValue();
var now = new Date();
var diff = (now-entry_date) / (24 * 60 * 60 * 1000); // Divide by number of milliseconds in a day
diff = Math.floor(diff); // Round down
s2.getRange(lastRow, 2).setValue(diff);
}

How to correct this script to don't run triggers on specific dates

Im currently using this script
function shouldRunTrigger() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var fiestas = ss.getSheetByName("x");
var data = fiestas.getRange(2,1,fiestas.getLastRow()-1,4).getValues();
var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
var date = new Date();
var day = days[date.getDay()];
var hours = date.getHours();
var FiestaEmpieza = date
var FiestaAcaba = date
for (var row in data){
FiestaEmpieza = data[row][2] ;
}
for (var row in data){
FiestaAcaba = data[row][3] ;
}
// Don't run from Friday 6pm until Saturday 10Pm
if ((day === "Fri" && hours >= 18) || (day === "Sat" && hours <= 21)){
return false;
}
// Dont turn from specific dates from Tab "x" from 6pm until 10pm
else if (date >= FiestaEmpieza && hours >= 18 && date <= FiestaAcaba && hours <= 21){
return false;
}
else {
return true;
}
}
The purpose of the script: I have to run some triggers every 5 mins, but if the day is between Friday 6pm and Saturday 10pm the trigger doesn't run This part is working.
I need also this to don't run in specific dates (line 31 of the script)
which takes dates from my spreadsheet Tab "x" , the Start date is Column C and the End date is Column D, and the data looks like this:
The problem I believe is the line 31 of the script
else if (date >= FiestaEmpieza && hours >= 18 && date <= FiestaAcaba && hours <= 21){
Which is not detecting the Dates and Hrs correctly , I'm not sure if the && are correct.
Any help on how to solve this please ?
I think this might work. If I can have access to your spreadsheet so that I can just copy the data then I would test it.
function shouldRunTrigger() {
var ss=SpreadsheetApp.getActiveSpreadsheet();
var sh=ss.getSheetByName("x");
var vA=sh.getRange(2,1,sh.getLastRow()-1,4).getValues();
var days=["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
var today=new Date();
var day=days[today.getDay()];
var hours=today.getHours();
if((day=="Fri" && hours>=18) || (day=="Sat" && hours<=22)){return false;}
for(var i=0;i<vA.length;i++){
var dt1=new Date(vA[row][2]).valueOf();
var dt2=new Date(vA[row][3]).valueOf();
if(today.valueOf()>=dt1 && hours >=18 && today.valueOf() <= dt2 && hours <= 21){
return false;
}
}
return true;
}
FiestaEmpeiza y FiestaAcaba will always be the last row because you loop through the date values and assign, but then don't perform any of your conditional checks. You need to consolidate the loops into one, and then move your if statements into the loop.
I recommend changing some of the variable names to be more descriptive and pass the trigger time to your function so that you can more easily test it.
Also, make sure that you maintain consistency with your date checks–date objects include time. The way you had it written, you were comparing dates objects, meaning that "April 1 # 4pm" is earlier than "April 1 # 4:01pm". So your condition could fail depending on the value you had defined in date. You can fix this simply by setting hours. (Be careful with time zone issues.)
function test_shouldRunTrigger() {
var triggerTime = new Date("Fri Apr 19 17:00:00 GMT+08:00 2019"); // Change the date to test
Logger.log(shouldRunTrigger(triggerTime));
}
function shouldRunTrigger(triggerTime) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("x");
var fiestas = sheet.getRange(2,1,sheet.getLastRow()-1,4).getValues();
var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
var triggerDay = days[triggerTime.getDay()]; // Day of the week
var triggerHour = triggerTime.getHours(); // Hour of the trigger
var triggerDate = new Date(triggerTime.setHours(0, 0, 0, 0)); // Set time to 00:00:00
Logger.log(fiestas)
for (var row in fiestas) {
var fiestaEmpieza = new Date(fiestas[row][2].setHours(0, 0, 0, 0)); // Set time to 00:00:00
var fiestaAcaba = new Date(fiestas[row][3].setHours(0, 0, 0, 0)); // Set time to 00:00:00
// Don't run from Friday 6pm until Saturday 10pm
if ((triggerDay === "Fri" && triggerHour >= 18) || (triggerDay === "Sat" && triggerHour <= 21)) {
return false;
} else if ( // Dont run from specific dates from Tab "x" from 6pm until 10pm
triggerDate >= fiestaEmpieza && // Compares dates and we know the times are all 00:00:00
triggerHour >= 18 &&
triggerDate <= fiestaAcaba && // Compares dates and we know the times are all 00:00:00
triggerHour <= 21
) {
return false;
} else {
return true;
}
}
}

How to target multiple specific days in this Google Apps Script

I have this script, it sends an email when the spreadsheet hasn't been modified by a specific time on set of days:
function checkWriting() {
const emailAddress = "your#email.com";
var now = new Date();
var day = now.getDay();
var hours = now.getHours();
//Set the days and between which hours to check
//Sun=0 Mon=1 Tue=2 Wed=3 Thu=4 Fri=5 Sat=6
if ((day >= 3) && (day <= 5) && (hours >= 18) && (hours <= 19)) {
// Get the dates
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var lastRow = sheet.getLastRow();
var formatDate = sheet.getRange(lastRow, 1).getValue().replace("at", "").replace("AM", "").replace("PM","") + " GMT+0100";
var lastWrite = new Date(formatDate);
var lastWriteDate = lastWrite.getFullYear() + "-" + lastWrite.getMonth() + "-" + lastWrite.getDate();
var nowDate = now.getFullYear() + "-" + now.getMonth() + "-" + now.getDate();
if (nowDate > lastWriteDate) {
// Send an email out
MailApp.sendEmail(emailAddress, "You didn’t write today.", "Get on that.");
}
}
}
Right now I have it set to run between Wednesday and Friday.
My question is how do I target lets say Monday, Wednesday, Friday?
Would I write it so I just have multiple separate functions? For example
function checkWritingMonday() {
const emailAddress = "your#email.com";
var now = new Date();
var day = now.getDay();
var hours = now.getHours();
//Set the days and between which hours to check
//Sun=0 Mon=1 Tue=2 Wed=3 Thu=4 Fri=5 Sat=6
if ((day = 1) && (hours >= 18) && (hours <= 19)) {
I realize I can probably also just have my trigger run only on Monday, Wed, or Friday. That's what I'm going to do in the interim.
I am just looking for a way to do it in the script.
You could simply create a more complex if, like this:
//Sun=0 Mon=1 Tue=2 Wed=3 Thu=4 Fri=5 Sat=6
if ((day == 1 || day == 3 || day == 5) && (hours >= 18) && (hours <= 19)) {

Automatic date if i change a cell

i know that's might a simple function, but i can't solve it.
I want to write a simple onEdit function with the following conditions:
If anything in a row (3 - xxx) is changed or updated, i want the actuel date in a specific column.
For example:
if I changed cell B10, I want the actuel date in cell G10. Also for an update in cell E10.
My head
function onEdit() {
var s = SpreadsheetApp.getActiveSheet;
var range = s.getActiveRange()
My loop over all rows is:
for(var i = 1; i<= range.getNumRows() ; i++){
var r = range.getCell(i, 1)
if( s.getName() == "Sheet1" ) {
My if-statement:
if( r.getColumn() == 2 ) {
var nextCell = r.offset(0, 2);
if( nextCell.getValue() === '' ) {//is empty?
var time = new Date();
time = Utilities.formatDate(time, "GMT+01:00", "HH:mm:ss MM/dd/yy");
nextCell.setValue(time);
}
};
};
I'll be happy if someone can helpme ;-)
function onEdit() {
var s = SpreadsheetApp.getActiveSheet();
// Instead of getting activeCell we get the whole range
var range = s.getActiveRange()
//Use For loop to go through each row and add the time Stamp
for(var i = 1; i<= range.getNumRows() ; i++){
var r = range.getCell(i, 1) //Assumption here is that data is pasted in one column only
// IF that is not always the case, you will have to get the range over which the data was pasted and select column 2
if( s.getName() == "Gesamt" ) { //checks that we're on the correct sheet
//var r = s.getActiveCell(); calling it again doesnt change its the value
// If it is first time keyword added, we will add the current date to "Date Added" Column
// We will if it is the first time the "Keyword" column has been written
for (var c = 1; c<=26; c++){
if( r.getColumn() == c) {
var k = 26 - c; //every updated time to the column 26 in the same row
var nextCell = r.offset(0, k);
//if( nextCell.getValue() === '' ) {//is empty?
var time = new Date();
time = Utilities.formatDate(time, "GMT+01:00", "HH:mm:ss MM/dd/yy");
nextCell.setValue(time);
};
};
}
}
}
There is no reason to loop on an on-edit trigger, as you will automatically be in the correct row and column every time there is an edit:
function onEdit(e){
var sheet = SpreadsheetApp.getActiveSheet();
var range = e.range; //gets edited range
var column = range.getColumn();
if (column < 3){ //stops if column is too low
return;
}
if (column > 6){ //stops is column is too high
return;
}
//else puts date in same row in column G
var row = range.getRow();
var time = new Date();
var stringTime = Utilities.formatDate(time, "GMT+01:00", "HH:mm:ss MM/dd/yy");
sheet.getRange(row, 7).setValue(stringTime);
}