Module 8: Scheduled Scripts

Week 5 • NetSuite SuiteScript 2.0 Training • ~60 minutes

🎯 Learning Objectives

1. What Are Scheduled Scripts?

Scheduled scripts run automatically at specified times without user interaction. Unlike User Event scripts that trigger on record actions, scheduled scripts run on a schedule (hourly, daily, weekly) or on-demand.

💡 Common Use Cases
  • Nightly batch processing
  • Weekly report generation
  • Data cleanup/archival
  • External system synchronization
  • Mass record updates

Script Structure

/**
 * @NApiVersion 2.1
 * @NScriptType ScheduledScript
 */
define(['N/search', 'N/record', 'N/runtime'], function(search, record, runtime) {
    
    function execute(context) {
        // context.type tells us how script was triggered
        // 'SCHEDULED', 'ON_DEMAND', 'USER_INTERFACE', 'ABORTED', 'SKIPPED'
        
        log.audit('Script Started', 'Type: ' + context.type);
        
        // Your batch processing logic here
        
        log.audit('Script Completed', 'Success');
    }
    
    return { execute: execute };
});

2. Queue System

Scheduled scripts don't run immediately at their scheduled time. They're placed in a queue.

⚠️ Important Queue Behavior
  • By default, you have 1 queue for scheduled scripts
  • Only one script runs per queue at a time
  • The scheduler checks for queued scripts every 30 minutes
  • Scripts scheduled for 5:00 PM might start at 5:00-5:30 PM

SuiteCloud Plus Queues

LevelQueuesUse Case
Standard1Light usage
Level 15Multiple concurrent scripts
Level 210Heavy batch processing
Level 315Enterprise workloads

3. Creating Scheduled Scripts

Step 1: Create the Script File

/**
 * @NApiVersion 2.1
 * @NScriptType ScheduledScript
 */
define(['N/search', 'N/email'], function(search, email) {
    
    function execute(context) {
        // Find overdue invoices
        var invoiceSearch = search.create({
            type: search.Type.INVOICE,
            filters: [
                ['status', 'anyof', 'CustInvc:A'], // Open
                ['duedate', 'before', 'today']
            ],
            columns: ['entity', 'tranid', 'total', 'duedate']
        });
        
        var count = 0;
        invoiceSearch.run().each(function(result) {
            log.debug('Overdue', result.getValue('tranid'));
            count++;
            return true;
        });
        
        log.audit('Complete', count + ' overdue invoices found');
    }
    
    return { execute: execute };
});

Step 2: Create Script Record

  1. Go to Customization → Scripting → Scripts → New
  2. Select your script file
  3. Save the Script Record

Step 3: Create Deployment

  1. On the Script Record, go to Deployments tab
  2. Click "New Deployment"
  3. Set Status: Testing or Released
  4. Configure Schedule (or leave blank for on-demand)
  5. Select Queue

Running On-Demand

To run immediately: Edit Deployment → Save and Execute

4. Governance Management

Scheduled scripts have a 10,000 unit governance limit. Monitor usage to prevent script termination:

function execute(context) {
    var script = runtime.getCurrentScript();
    
    var customerSearch = search.create({...});
    
    customerSearch.run().each(function(result) {
        // Check remaining governance
        var remaining = script.getRemainingUsage();
        
        if (remaining < 500) {
            log.audit('Low Governance', 'Stopping early. Remaining: ' + remaining);
            return false; // Stop processing
        }
        
        // Process record (uses governance)
        processCustomer(result);
        
        return true;
    });
}

Common Governance Costs

OperationUnits
record.load()10
record.save()20
search.create()5
search.lookupFields()1
email.send()20

5. Rescheduling (Checkpoint/Resume)

For large datasets, save progress and reschedule:

function execute(context) {
    var script = runtime.getCurrentScript();
    var startIndex = script.getParameter('custscript_start_index') || 0;
    
    var processed = 0;
    var search = search.create({...});
    
    search.run().each(function(result) {
        if (script.getRemainingUsage() < 500) {
            // Reschedule with new start point
            var taskId = task.create({
                taskType: task.TaskType.SCHEDULED_SCRIPT,
                scriptId: 'customscript_my_script',
                deploymentId: 'customdeploy_my_script',
                params: { 'custscript_start_index': startIndex + processed }
            }).submit();
            
            log.audit('Rescheduled', 'Task ID: ' + taskId);
            return false; // Stop this execution
        }
        
        processRecord(result);
        processed++;
        return true;
    });
}
✅ Best Practices
  • Schedule during off-peak hours (6PM - 6AM PST)
  • Offload heavy processing from User Event scripts to Scheduled
  • Monitor governance and implement checkpoints
  • Log start, progress, and completion

🏋️ Practice Exercises

Exercise 1: Basic Scheduled Script

Create a scheduled script that searches for Customers created in the last 7 days and logs their names.

Exercise 2: Governance Monitoring

Modify your script to check remaining governance every 50 records and log the count.

🎯 Key Takeaways

  • Scheduled scripts run automatically on a schedule or on-demand
  • Scripts are queued, not immediate - scheduler runs every 30 min
  • 10,000 governance units per execution
  • Use getRemainingUsage() to monitor governance
  • Implement checkpoint/reschedule for large datasets
  • Schedule during off-peak hours for better performance