Skip to content

Instantly share code, notes, and snippets.

@aviskase
Last active May 16, 2020 07:39
Show Gist options
  • Save aviskase/c986a50fd0d2a24f98302201fcdc9fd7 to your computer and use it in GitHub Desktop.
Save aviskase/c986a50fd0d2a24f98302201fcdc9fd7 to your computer and use it in GitHub Desktop.
Google Apps Script: create tasks in Amazing Marvin in random intervals
// Trigger for this script should be run DAILY
var TARGET_EMAIL = '<AMAZING MARVIN IMPORT EMAIL>';
var MILLIS_PER_DAY = 1000 * 60 * 60 * 24;
var TASKS = [
{ // Task will be created in ranges from 5 to 10 after last created date. E.g. if last created = May 10, next task will be created between May 15 and May 20
id: '<TASK ID>',
range_start: 5,
range_end: 10,
subject: '<TASK NAME>',
body: '<TASK NOTE>'
}
];
function getNow() {
return new Date(date_to_str(new Date()));
}
function date_to_str(date) {
var timeZone = Session.getScriptTimeZone();
return Utilities.formatDate(date, timeZone, 'MMMM dd, yyyy 12:00:00 Z');
}
function createTask(task, props) {
var last_run = props.getProperty(task['id']);
var now = getNow();
if(!last_run) {
Logger.log('First run for task with id = %s ', task['id']);
var offset = Math.floor((task['range_start'] + task['range_end']) / 2);
last_run = new Date(now - offset * MILLIS_PER_DAY);
Logger.log('Set last run to = %s', date_to_str(last_run));
props.setProperty(task['id'], date_to_str(last_run));
} else {
last_run = new Date(last_run);
}
var range_start = new Date(last_run.getTime() + task['range_start'] * MILLIS_PER_DAY);
var range_end = new Date(last_run.getTime() + task['range_end'] * MILLIS_PER_DAY);
var should_be_created = now >= range_end || (now >= range_start && Math.random() >= 0.5)
if(should_be_created) {
Logger.log('Task with id = %s was created', task['id']);
GmailApp.sendEmail(TARGET_EMAIL, task['subject'], task['body']);
props.setProperty(task['id'], date_to_str(now))
}
}
function run() {
var props = PropertiesService.getScriptProperties();
TASKS.forEach(function(task) {
createTask(task, props);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment