Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

You can schedule

...

the script execution

...

at a specific date and time, or on a regular basis with a

...

certain frequency

To create a scheduled script,

...

complete the steps below:

  1. Navigate to System Scheduler → Schedule Script.
  2. Click New and fill in the fields.
  3. Click Save or Save and

...

  1. exit to apply the changes.

Schedule script form fields

Field

Mandatory

Description

NameYSpecify the scheduled script name.
Run asYSelect a user to run the script

...

as. Make sure that the specified user has sufficient rights to perform CRUD transactions, defined in the script.
ActiveNSelect this checkbox to

...

activate the script

...

.
Job

...

Add a description of actions performed by the script.
ScriptNType in a script to execute.
Run frequencyY

Select the run frequency. Available options:

  • On

...

  • Demand – the script is only executed upon a user's request. If this option is selected, the Execute button appears in the upper right corner of the form. Click it to run the script.
  • Periodically – the script is run regularly with a frequency set by the Run period field.
  • Once – the script is run once on the date and time specified in the Run date and time field.
  • Daily – the script is run daily at the time specified in the Run time field.
  • Weekly – the script is run each week on the selected Day of week at the time specified in the Run time field.
  • Monthly – the script is run each month on the selected Day of month at the time specified in the Run time field.
Run periodY

Specify the period between script runs

This field appears when the Periodically option is selected in the Run frequency field.

...

(days, hours, minutes, or seconds)

...

.

Info

...

This field appears when the 

...

Periodically option is selected in the Run frequency

...

 field.


Run timeY

...

Specify the time when to execute a script.

...

The script is executed regularly at this time.

...

Info

This field appears when the Daily, 

...

WeeklyMonthly options are selected in the Run frequency field.


Run date and timeY

Specify the date and time of the script execution.

You can set the current date and time by clicking Now in the date-picker.

Image Modified

...

Info

This field appears when

...

 Periodically or Once options are selected in the Run frequency field.


Day of weekY

Specify a day of the week on which the script should run. For example, select Friday.

...

Info

...

This field appears when the 

...

Weekly option is selected in the Run frequency field.


Day of monthY

Specify a day of the month on which the script should run. For example, select 13 for the 13th day of the month.

Скрипты по расписанию Schedule Scripts

Скрипты по расписанию позволяют выполнять серверные скрипты в конкретное время и с определённой периодичностью. Например, отправлять отчёт c числом просроченных задач третьего числа каждого месяца.

Переход в список скриптов по расписанию через навигатор: System Scheduler -> Schedule Script.

Поля формы Schedule Script:

...

Поле

...

Описание

...

Name

...

Название скрипта по расписанию

...

Run as

Пользователь, от лица которого будет запускаться скрипт. Убедитесь, что у указанного пользователя достаточно прав на совершение CRUD операций, определённых в скрипте.

...

Active

...

Активность скрипта по расписанию

...

Job

...

Текстовое описание действий, выполняемых в скрипте

...

Script

...

Серверный скрипт для запуска

...

Run frequency

...

Частота запуска скрипта

...

Run period

...

Период запуска скрипта. Доступные опции:

  • On-Demand / По запросу
  • Periodically / Периодически
  • Once / Единожды
  • Daily / Ежедневно
  • Weekly / Еженедельно
  • Monthly / Ежемесячно

...

Run date and time

...

Время и дата запуска скрипта с периодом запуска "Единожды"

...

Timezone

...

Часовой пояс для даты и времени, указанных в поле Run date and time

...

Run time

...

Время запуска в часовом поясе UTC

...

Day of week

...

Один из дней недели для запуска скрипта

...

Day of month

...

один из дней месяца для запуска скрипта

Info

This field appears when the Monthly option is selected in the Run frequency field

В качестве альтернативы скриптам, запускаемым периодически могут использоваться отложенные системные события, в скрипте которых будет выполняться планирование будущего события и выполнение основного скрипта (который задаётся в поле Schedule script -> Script). Скрипты системных событий рассматриваются в статье.

Особенности настройки скриптов по расписанию

  1. При написании скриптов, для изменения/удаления записей конфигурации через скрипт создайте отдельного пользователя User и производите установку нужного приложения, перед изменением/удалением записи:(function executeScheduleScript() {  const RUN_AS_USER_ID = '155964310500000026'; // Schedule script -> Run as -> ID  preference.addQuery('name', 'application');  preference.setLimit(1);  if (preference.next()) {    preference.update();    preference.user_id = RUN_AS_USER_ID;    preference.value = ITSM_APPLICATION;  }})()
  2.   // update/delete vcs enabled records ...
  3.     preference.insert();
  4.     preference.name = 'application';
  5.   } else {
  6.     preference.value = ITSM_APPLICATION;
  7.   preference.query();
  8.   preference.addQuery('user_id', RUN_AS_USER_ID);
  9.   const preference = new SimpleRecord('sys_user_preference');
  10.   const ITSM_APPLICATION = '156950344216170038';
  11. Для получения токена текущего пользователя в теле скрипта (пользователя, указанного в поле Run as) невозможно использовать метод getAccessToken(). ​​​​​​Для получения токена используйте выборку:const tokenRec = new SimpleRecord('user_token');tokenRec.orderByDesc('sys_created_at');tokenRec.query();const tokenValue = tokenRec.token;
  12. tokenRec.next();
  13. tokenRec.setLimit(1);
  14. tokenRec.addQuery('user_id', '155964310500000026'); // Schedule script -> Run as -> ID
  15. Создавайте скрипты по расписанию в неактивном состоянии. После завершения настройки скрипта измените активность через отдельное сохранение формы скрипта.
  16. Выполняйте перенос скрипта между экземплярами в неактивном состоянии.

Нестандартное использование скриптов по расписанию

При выполнении серверного скрипта с обновлением большого числа записей возможно возникновение сообщений 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)}`);

...

.