Skip to main content

Writing to a script processing table

Note: see my more recent update on this topic here
---

how it works:

- a business rule fires onafter
- a script is written in string format to a special table (scheduled script runner) which is then processed by manually executing a scheduled job following a small delay

Business rule script:

(function executeRule(current, previous /*null when async*/) {
    gs.log('sending attachment to FJ', 'busRule:Send Attachment to Vendor');
   
   
    //--queue a script to update the send flag back to false
    //--scheduling the update prevents interference with the file being sent  
        var GR_schScript = new GlideRecord('u_scheduled_script_runner');
        var s_script='';
        s_script=s_script+'var gr=new GlideRecord("u_task_integration_attachments");\r\n';
        s_script=s_script+'gr.addQuery("sys_id","' + current.sys_id + '");\r\n';
        s_script=s_script+'gr.query();\r\n';
        s_script=s_script+'if (gr.next()){\r\n';
        s_script=s_script+'gr.u_send_attachment = false;\r\n';
        s_script=s_script+'gr.u_attachment_sent = true;\r\n';
        s_script=s_script+'gr.update();\r\n';
        s_script=s_script+'}\r\n';
        GR_schScript.newRecord();
        GR_schScript.u_script_to_run=s_script;
        GR_schScript.u_record_table='u_task_integration_attachments';
        GR_schScript.u_record_sysid=current.sys_id;
        GR_schScript.u_script_to_execute=s_script;
        var sch_scr=GR_schScript.insert();
       
    gs.sleep(50);
    var rec = new GlideRecord('sysauto_script');
    rec.get('name', 'TidyUpTaskIntegrationsAttachments');
    SncTriggerSynchronizer.executeNow(rec);
   
        gs.addInfoMessage(gs.getMessage('attachment.send'));
    })(current, previous);


Scheduled job script:
//--DO NOT CHANGE THE NAME OF THIS SCHEDULED JOB! as executed on demand from business rule--//

var gr = new GlideRecord("u_scheduled_script_runner");
gr.addQuery("u_record_table" , "u_task_integration_attachments");
gr.addQuery("u_status", "pending");
gr.orderBy("u_sequence");
gr.query();
gs.log('START JOB: ROW COUNT: ' + gr.getRowCount(), 'schjob:_attach');
//--use arrays, as the gliderecord gets temperamental with glidescopedevaluator!
var arrSYSIDS_str='';
while (gr.next()){
    arrSYSIDS_str+= gr.sys_id+","; 
}
arrSYSIDS_str= arrSYSIDS_str.substring(0, arrSYSIDS_str.length - 1);
var arrSYSIDS=arrSYSIDS_str.split(',');

for (i=0;i<arrSYSIDS.length;i++){
   eval_script(arrSYSIDS[i]);
}
for (y=0;y<arrSYSIDS.length;y++){
   setRowProcessed(arrSYSIDS[y]);
}

//--tidy up:
var delQuery='u_status=processed^sys_created_on<javascript:gs.beginningOfLastMonth()';
var grDel = new GlideRecord("u_scheduled_script_runner");
grDel.addQuery(delQuery);
grDel.deleteMultiple();

gs.log('START JOB: ROW COUNT: ' + gr.getRowCount(), 'schjob:attach');

function eval_script(sysid){
  var gr = new GlideRecord("u_scheduled_script_runner");
  if (gr.get('sys_id', sysid)){
     var obj_evaluator = new GlideScopedEvaluator();
     var res=obj_evaluator.evaluateScript(gr, 'u_script_to_execute');
     //gs.print(res);
  }
}

function setRowProcessed(sysid){
    var gr = new GlideRecord("u_scheduled_script_runner");
    if (gr.get('sys_id', sysid)){
        gr.u_status='processed';
        gr.update();
    }
}

Script processing table(u_scheduled_script_runner):


note: 'script to execute' field is of type 'script'

Comments

  1. The approach of using a script-processing table to defer updates is an interesting way to avoid interfering with an attachment-processing operation. The example demonstrates how an asynchronous business rule can store a script for later execution, allowing attachment flags to be updated after a short delay. One important consideration is ensuring that queued scripts execute reliably and that failures can be traced without leaving records in an inconsistent state.

    Understanding how business rules interact with scheduled execution is useful when building event-driven integrations, and the example provides a practical context for exploring Javascript Online Training concepts such as scripting, execution flow, and record updates in ServiceNow.

    ReplyDelete
  2. For developers looking to strengthen their scripting foundations, Javascript Online Course material can help build a clearer understanding of variables, string construction, and conditional logic used in examples like this. The key takeaway is to manage deferred operations carefully, with appropriate error handling and execution controls.

    ReplyDelete

Post a Comment

Popular posts from this blog

URL link in addInfoMessage

var ga=new GlideAjax('gld_HR_ajax'); ga.addParam('sysparm_name', 'checkEmployeeNumber_hrProfile'); ga.addParam('sysparm_hrprofilenumber', g_form.getValue('number')); ga.addParam('sysparm_employeenumber', newValue); ga.getXMLAnswer(function(answer) { if (answer!='undefined' && answer!=''){ var navURL="<a style='text-decoration:underline;color:blue' href=hr_profile.do?sysparm_query=number=" + answer + ">" + answer + "</a><img width='3' src='images/s.gif'/>"; var sMsg='The employee number entered already exists on another HR Profile ' + navURL; //alert(sMsg); g_form.showErrorBox('employee_number', 'error - please check'); g_form.addInfoMessage(sMsg); } });

ServiceNow check for null or nil or empty (or not)

Haven't tested these all recently within global/local scopes, so feel free to have a play! option 1 use an encoded query embedded in the GlideRecord , e.g.  var grProf = new GlideRecord ( 'x_cls_clear_skye_i_profile' ); grProf . addQuery ( 'status=1^ owner=NULL ' ); grProf . query (); even better use the glideRecord  addNotNullQuery or addNullQuery option 2 JSUtil.nil / notNil (this might be the most powerful. See this link ) example: if ( current . operation () == 'insert' && JSUtil . notNil ( current . parent ) && ! current . work_effort . nil ())  option 3 there might be times when you need to get inside the GlideRecord and perform the check there, for example if the code goes down 2 optional routes depending on null / not null can use gs.nil : var grAppr = new GlideRecord ( 'sysapproval_approver' ); var grUser = new GlideRecord ( 'sys_user' ); if ( grUser . get ( 'sys_id' , current . approver )){...