Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Creating Metric Instances through Scheduled jobs

julienr
Mega Contributor

Hello everyone.

So, for reporting reasons, I need each first day of the month to create a new metric instance from a specific definition.

So of course I thought of creating a scheduled job, but for some reason it goes through everything but my instances are not created...

Would anyone have an idea as to where I'm taking a wrong turn?

Thank you so much.

here's my code:

createMetricInstances();

function createMetricInstances(){

  var value = 'FollowUp Indicator not breached';

//Query on the task sla table to know exactly how many instances I need to create

  var gr = new GlideRecord("task_sla");

  gr.addQuery("sla", "37b3b0ea3774e600894b98a543990e29");

  gr.addActiveQuery();

  gr.query();

  while (gr.next()) {  

// Here I tried several ways to pass values to definition and current. Nothing worked

  var newmi = new MetricInstance('c083fcaa3774e600894b98a543990e48', gr);

  /*var mi = new MetricInstance(def, gr);

  var newmi = mi.getNewRecord();

  newmi.definition = 'c083fcaa3774e600894b98a543990e48';

  newmi.id = gr.sys_id;*/

  var now = new GlideDateTime();

  newmi.start = now;

  if (gr.has_breached == 'true'){

  value = 'FollowUp Indicator breached';

}

  newmi.value = value;

  newmi.insert();

  //I've set a serie of logs here and there which I erased here for easier reading - They all log correctly...

  }

}

8 REPLIES 8

Kalaiarasan Pus
Giga Sage

julienr
Mega Contributor

So, I managed to solve this using a related conversation I found: The script is aimed to be a scripted scheduled job and is functional



createMetricInstances();



function createMetricInstances(){


  var value;


  var def = 'c083fcaa3774e600894b98a543990e48';//Replace value with the MetricDef you want to instanciate


  var gr = new GlideRecord("task_sla");


  gr.addQuery("sla", "37b3b0ea3774e600894b98a543990e29");//Replace value with the sla definition sys_id


  gr.addActiveQuery();


  gr.query();


  //gs.log('JU:Scheduled job found '+gr.getRowCount()+' rows');


  while (gr.next()) {


  value = 'FollowUp Indicator not breached';


  var newmi = new GlideRecord('metric_instance');


  newmi.initialize();


  newmi.definition = def;


  newmi.id = gr.sys_id;


  newmi.start = gs.nowDateTime();


  if (gr.has_breached == true)


  value = 'FollowUp Indicator breached';


  newmi.value = value;


  newmi.insert();


  }


}


jleyco
Mega Contributor

This was very helpful!



However, I was wondering how you would modify this to NOT create a metric instance if there is already one for that 'ID' and metric definition?


You can find that in the original link provided. I would have checked if the record already exists before inserting a new record.