You can schedule a script execution to perform them on a regular basis with a specified periodicity.
To create a scheduled script, please complete the steps below:
Schedule script form fields
Field | Mandatory | Description |
---|---|---|
Name | Y | Specify the scheduled script name. |
Run as | Y | Select a user to run the script execution. |
Active | N | Select this checkbox to make the script active or inactive. |
Job | N | Type a description of actions performed by the script. |
Script | N | Type a script to execute. |
Run frequency | Y | Available options:
|
Run period | Y | This field appears when the Periodically option is selected in the Run frequency field. Customize the period (days, hours, minutes, or seconds) in a preferred combination using the input fields |
Run time | Y | This field appears when the Daily, Weekly, Monthly options are selected in the Run frequency field. Specify the time when to execute a script. Then the script will run regularly at this time. |
Run date and time | Y | This field appears when Periodically, Once options are selected in the Run frequency field. Specify the date and time of the script execution. You can set the current date and time by clicking Now in the date-picker. |
Day of week | Y | This field appears when the Weekly option is selected in the Run frequency field. Specify a day of the week on which the script should run. For example, select Friday. |
Day of month | Y | This field appears when the Monthly option is selected in the Run frequency field. Specify a day of the month on which the script should run. For example, select 13 for the 13th day of the month. |
Скрипты по расписанию позволяют выполнять серверные скрипты в конкретное время и с определённой периодичностью. Например, отправлять отчёт c числом просроченных задач третьего числа каждого месяца.
Переход в список скриптов по расписанию через навигатор: System Scheduler -> Schedule Script.
Поля формы Schedule Script:
Поле | Описание |
Name | Название скрипта по расписанию |
Run as | Пользователь, от лица которого будет запускаться скрипт. Убедитесь, что у указанного пользователя достаточно прав на совершение CRUD операций, определённых в скрипте. |
Active | Активность скрипта по расписанию |
Job | Текстовое описание действий, выполняемых в скрипте |
Script | Серверный скрипт для запуска |
Run frequency | Частота запуска скрипта |
Run period | Период запуска скрипта. Доступные опции:
|
Run date and time | Время и дата запуска скрипта с периодом запуска "Единожды" |
Timezone | Часовой пояс для даты и времени, указанных в поле Run date and time |
Run time | Время запуска в часовом поясе UTC |
Day of week | Один из дней недели для запуска скрипта |
Day of month | один из дней месяца для запуска скрипта |
В качестве альтернативы скриптам, запускаемым периодически могут использоваться отложенные системные события, в скрипте которых будет выполняться планирование будущего события и выполнение основного скрипта (который задаётся в поле Schedule script -> Script). Скрипты системных событий рассматриваются в статье.
При выполнении серверного скрипта с обновлением большого числа записей возможно возникновение сообщений 504. Ошибка связана с ограничением времени выполнения для REST запросов (Time Out).
Для решения используйте периодически запускаемый скрипт дс обновлением части записей. Пример скрипта:
const MESSAGE_PREFIX = '[Update User Records]';
const TABLE_NAME = 'user';
const TABLE_QUERY_CONDITION = '(field_name!=field_value)'; // query condition
const QUERY_LIMIT = 500;
let lastRecord = '1';
const lastTwoMinutes = new SimpleDateTime();
lastTwoMinutes.addSeconds(-120); // 2 minutes
const logMessage = new SimpleRecord('sys_log');
logMessage.addQuery('level', 'debug'); // debug level
logMessage.addQuery('sys_created_at', '>', lastTwoMinutes.getValue());
logMessage.addQuery('message', 'startswith', MESSAGE_PREFIX);
logMessage.orderByDesc('sys_created_at');
logMessage.setLimit(1); // newest record
logMessage.selectAttributes('message');
logMessage.query();
if (logMessage.next()) {
if (logMessage.message.match(/(?<=Last record: )(\d{18})/g)) {
lastRecord = logMessage.message.match(/(?<=Last record: )(\d{18})/g)[0];
}
}
ss.debug(`${MESSAGE_PREFIX}\nLast record: ${lastRecord}`);
const record = new SimpleRecord(TABLE_NAME);
record.orderBy('sys_id');
record.addQuery('sys_id', '>', lastRecord);
record.addEncodedQuery(TABLE_QUERY_CONDITION);
record.setLimit(QUERY_LIMIT);
record.query();
let updatedRecords = [];
while (record.next()) {
lastRecord = record.sys_id;
// record.field_name = 'field_value';
const updatedRecordId = record.update();
if (updatedRecordId) {
updatedRecords.push(updatedRecordId);
}
}
ss.debug(`Last record: ${lastRecord}`);
ss.info(`${updatedRecords.length} records updated:\n\n${JSON.stringify(updatedRecords, null, 2)}`);