logo

NJP

Trigger metric retroactively

Import · Mar 29, 2017 · article

Again a little code tip for those that may need it. Nothing hard to create yourself, but may be faster this way.

I had to change a metric that was running calculations on the wrong information, which in itself was not problem; what was an issue were the reports that used the metric, as they used incorrect data. So, I needed a way to trigger creation of new metric instances.

I used Scripts - Background to run two different scripts. The first looked for all instances of a specific metric and removed these. The second took all tasks that fit the query and for each triggered the event found in the metric business rule with appropriate parameters.

Before the scripts, here are some points:

  • Metric instances (metric_instance_list.do) has the task sys_id as their "ID", be sure to send this to find appropriate metric instance if needed.
  • It is very easy to dotwalk metric instance, as ID is the task and Definition is the Metric Definition (not sys_id, but a reference).
  • To search for all occurences of a definition in metric instance, use definition.name (if the name is what you use as identifier in your script).
  • To find what parameters trigger a metric, check the Metric System Logs, may help you if the variable information is hard to read.

Script to find all metric instances of a specific definition based on name:

        //Access table with metric instances

var met = new GlideRecord('metric_instance');

        //Get all metric instances created since beginning of this year (GMT)

met.addQuery('sys_created_on', '>', gs.beginningOfThisMonth());

        //Get all metric instances that are created by a metric definition with the word test in the name

met.addQuery('definition.name', 'CONTAINS', 'test');

met.query();

        //Show how many results found

gs.print('Found ' + met.getRowCount());

while (met.next()) {

      //Do what you need to with the metric instances.

}

Script to trigger creation of new metric instance with task ID:

var check = new GlideRecord('task');

      //Get all tasks that were closed this year

check.addQuery('closed_at','>',gs.beginningOfThisYear());

check.query();

gs.print('Found '+check.getRowCount());

while(check.next()){

        //Trigger metric.update with the task, send the trigger parameters

        //These are normally fetched through variables and commands, here we send them with static data

gs.eventQueue('metric.update', check, '[state,active]', check.sys_mod_count, 'metric_update');

}

As always, these are my current findings and only meant to help others resolve their quandaries quicker.

With regards

Anton Lindblad

View original source

https://www.servicenow.com/community/developer-articles/trigger-metric-retroactively/ta-p/2330214