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.x
 * @NScriptType ScheduledScript
 */
define(['N/search', 'N/record'], 
    function(search, record){
        return {
            execute: function (context)
            {
                var filter1 = search.createFilter({
                    name: 'mainline', 
                    operator: search.Operator.IS, 
                    values: true
                });
                var srch = search.create({
                    type: search.Type.SALES_ORDER, 
                    filters: [filter1], 
                    columns: []
                    });
 
                var pagedResults = srch.runPaged();
 
                pagedResults.pageRanges.forEach(function(pageRange){
                    var currentPage = pagedResults.fetch({index: pageRange.index});
                    currentPage.data.forEach(function(result){
                        var so = record.load({
                            type: record.Type.SALES_ORDER, 
                            id: result.id
                        });
                    //UPDATE so FIELDS>
                    so.save()
                    });
                });
            }
        }
    }); 

        

To fix scripts like this, check out Example: A Robust Scheduled Script and Example 5: A Robust Map/Reduce Script Example.

General Notices