Example: A Problematic Scheduled Script
Scheduled scripts often search for data, then process the results.
In this example, the script updates each sales order in the system. The filter1 filter ensures that the search returns exactly one entry per sales order. But if the script is stopped in the middle and restarted, some sales orders might get updated twice.
To avoid data issues from re-processing, make your script's operations idempotent. They should give the same result even if run more than one time (like stopping duplicate records). Or, your script should be able to fix mistakes, like removing duplicates if they happen.
The example script isn't idempotent, so many sales orders could get updated twice, possibly doubling a price from a repeated run.
/**
* @NApiVersion 2.1
* @NScriptType ScheduledScript
*/
define(['N/search', 'N/record'], (search, record) => {
return {
execute: () => {
const filter1 = search.createFilter({
name: 'mainline',
operator: search.Operator.IS,
values: true
});
const srch = search.create({
type: search.Type.SALES_ORDER,
filters: [filter1],
columns: []
});
const pagedResults = srch.runPaged();
pagedResults.pageRanges.forEach((pageRange) => {
const currentPage = pagedResults.fetch({ index: pageRange.index });
currentPage.data.forEach((result) => {
const so = record.load({
type: record.Type.SALES_ORDER,
id: result.id
});
//UPDATE so FIELDS>
so.save();
});
});
}
};
});
To fix scripts like this, see Example: A Robust Scheduled Script and Example 5: A Robust Map/Reduce Script Example.