简体   繁体   中英

Google Spreadsheet Triggers

I'm trying to create a trigger that activates on weekdays only and at a specific time, but I don't know what I'm doing wrong. Here is my code.

function createTriggers() {
    var days = [ScriptApp.WeekDay.MONDAY, ScriptApp.WeekDay.TUESDAY,
                ScriptApp.WeekDay.WEDNESDAY, ScriptApp.WeekDay.THURSDAY,
                ScriptApp.WeekDay.FRIDAY];

    var d = new Date();
    var time = d.toLocaleTimeString();

    if (time == '3:05:00 PM EDT') {
        for (var i = 0; i < days.length; i++) {
            ScriptApp.newTrigger(Lunch1)
            .timeBased().onWeekDay(days[i])
            .everyMinutes().create();
        }
    }
}

You should do something like this:

function createTriggers(func, hour) {
  var weekdays = [ScriptApp.WeekDay.MONDAY, ScriptApp.WeekDay.TUESDAY,
               ScriptApp.WeekDay.WEDNESDAY, ScriptApp.WeekDay.THURSDAY,                                            
               ScriptApp.WeekDay.FRIDAY];

  for (var dayIndex in weekdays) {
    var day = weekdays[dayIndex];

    ScriptApp.newTrigger(func).timeBased()
      .onWeekDay(day).atHour(hour).create();
  }
}

This code creates a trigger for weekdays in a specific time calling the func function.

I'm guessing that you mean you want to make it so a function is triggered (runs) every weekday at a certain time of the day. Here's what I would do.

First, in the Script Editor:

  1. Go to Resources - Current Project's Triggers

  2. Click Add a new trigger

  3. Select the function that you want to be triggered

  4. Change the next box to "Time-driven"

  5. Change the next box to "Hour timer"

  6. Then change the last box to "every hour"

Then at the very beginning of your function, add this code:

var d = new Date(); 
if (d.getDay() == 6 || d.getDay() == 0) return;
// more info here: http://www.w3schools.com/jsref/jsref_getday.asp

That will stop the rest of the script from running if it's a Saturday or Sunday.

Then, say you want the script to only run at one specific time each weekday, you could set the time-driven trigger to "Every minute" and then add another if statement after the one above:

if (d.getHours() != 15 && d.getMinutes() != 5) return;

That will stop the rest of the script from running if it's not exactly 15:05 (3:05 PM).

This is definitely not the most efficient way to do this, but it works.

Also, this is worth mentioning: I'm not sure if there's anything that would prevent you from triggering the script every minute. Google does impose quotas for what your scripts can do, but I didn't see anything about how many times a script can be triggered in a day. Here's the chart: https://developers.google.com/apps-script/guides/services/quotas

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM