Real Time use for Turnstile activity in workflow

SHAIK18
Mega Contributor

Hi,

Can any one give me real time use case for the Turnstile activity in workflow 

Thanks in advance.

 

3 REPLIES 3

Saurabh singh4
Kilo Guru

Hi shaik

Please check this article you'll get some clarification

Continuing in the vein of workflow looping I found that I wanted a better Turnstile Activity.   One that would take a variable rather than a "hard-coded" integer.     To do this would require modifying the out-of-the-box Turnstile Activity to accept a variable.

 

NOTE: BEST PRACTICE: Try to avoid modifying and saving back down over the top of an existing out-of-the-box anything in ServiceNow. Any future upgrade to the software will be skipped to preserve your changes.   Always make a copy and use that instead.

 

We will be doing the following for this lab:

 

  1. Make a copy of the existing Turnstile Activity
  2. Modifying the Turnstile Activity to accept a variable of our choosing rather than an integer.
  3. Creating a workflow to demonstrate looping using our enhanced Turnstile Activity (we will be using the initialize activity from my previous lab.

 

Assumption: That you have worked with and created ServiceNow Workflows before.   Also, you should probably play with this in your personal instance until you get proficient with the concept.   Just saying.

 

NOTE: We are going to create all of our activities first and wire them all together as the last step.

 

NOTE: I highly recommend creating an Update Set to capture your enhanced Turnstile Activity so that you can port it around if you want.   I have placed everything from this lab out on the share if you want to download it.

 

 

Lab 1.1 — Enhancing the Turnstile Activity

 

1. Navigate to Workflow → Administration â†’ Activity Definitions. This will open the Activity Definitions list view.

 

2. Search for the Turnstile Activity, and click on the link to open the activity.   This will open the activity definition form.

      a. Change the name field to be: Turnstile (Enhanced)

      b. Right-Click on the form header to display the context menu.

      c. Click on Insert and Stay.   Make sure you do this or you will be modifying the original!   This will make a copy of the original activity that will be yours to modify.   Otherwise you will "own" the out-of-the-box version, and it WILL be skipped on your next ServiceNow upgrade.   If you do save down over the original simply revert to the previous version and try again.

 

image

 

      d. In the Script field scroll down and change script to the following:

 

var Turnstile__Enhanced_ActivityHandler = Class.create();

Turnstile__Enhanced_ActivityHandler.prototype = Object.extendsObject(WFActivityHandler, {

         

                      initialize: function() {

                                              var schpdName = 'iterations_' + activity.activity.sys_id;

                                              WFActivityHandler.prototype.initialize.call(this);

                                              if (!workflow.scratchpad[schpdName]) {

                                                                      workflow.scratchpad[schpdName] = 1;

                                              }

                      },

         

                      onExecute: function() {

                                              // implement activity definition code here

                                              var schpdName = 'iterations_' + activity.activity.sys_id;

                                 

                                              var iterCountVar = parseInt(workflow.scratchpad[schpdName], 10);

                                              var iterAllowedVar = parseInt(this.js(activity.vars.iterations), 10);

 

                                              if (iterCountVar > iterAllowedVar) {

                                                                      //You've iterated too many times...stop iterating

                                                                      activity.result = 'cancel';

                                                         

                                              } else {

                                                                      //Still iterating

                                                                      iterCountVar ++;

                                                         

                                                                      workflow.scratchpad[schpdName] = iterCountVar;

                                                         

                                                                      activity.result = 'continue';

                                              }

                      },

         

                      type: 'Turnstile__Enhanced_ActivityHandler'

});

     

 

NOTE:   If you look careful you will notice that the following line has been modified:

 

var iterAllowedVar = parseInt(this.js(activity.vars.iterations), 10);

 

The this.js(…) will take whatever variable is fed to it and convert it to the value contained in that variable.   This will be important when we go to use the new activity in our workflow.

 

      e. Right-click on the form menu to bring up the context menu.   Click save to save the script change.

 

3. Now go to the bottom of our Activity definition.   You will notice that there are no variables or conditions defined.   These were not copied with our activity, and will need to be put back (with a very slight modification).

 

4. On the Activity Variables tab click the New button.

 

5. Fill out the form with the following:

 

      a. Column Name: iterations

      b. Label: Allowed Iterations

      c. Type: String         <- Here is our "slight" modification.   Previously this was Integer

      d. Order: 100

      e. Max length: 100   <- This is important as we will be putting a variable in this field now.

      f. Click the Submit button to save your new variable.

 

6. Click on the Condition Defaults tab.

 

7. Click on the New button.   We will be creating two new defaults.

 

8. Fill out the form with the following:

 

      a. Name: Continue

      b. Activity definition: Turnstile (Enhanced)

      c. Condition: activity.result == 'continue'

      d. Order: 100

      e. Short Description: Continue iterating

      f. Right-click on the form header to bring up the context menu and click Save to save your new Continue condition default.

 

9. Now change the form to the following:

 

      a. Name: Cancel

      b. Activity definition: Turnstile (Enhanced)

      c. Condition: activity.result == 'cancel'

      d. Order: 200

      e. Short Description: You've looped too many times...cancel it...

      f. Right-click on the form header to bring up the context menu and click Insert to save your new Cancel condition default.

 

You have now completed your new enhanced Turnstile Activity!   Congratulations!

 

 

Lab 1.2 — Using the Turnstile Activity

 

1. Navigate to Workflow â†’ Workflow Editor.   This will open the workflow editor.

 

      a. In the Workflow Navigation column click on the plus symbol to create a new workflow

 

image

 

2. Create a new workflow

 

a. Name: Enhanced Turnstile Example

b. Table: Global

c. Take all other defaults

d. Click the Submit button to create the workflow

 

3. On the Workflow Core tab, navigate to Utilities

 

4. Drag out a Run Script Activity on to the desktop.

 

Here we will be initializing our loop.   We will load a specified number of records from the Incident table.   Store these into a scratchpad variable.   The number of times to loop will be the number of records.   We will start with 0 as the first number.   Notice that there is a slight tweak to the count variable from what we did in the last lab.   This is because the Turnstile is acting on the "end" of things and loops one more time than we would like.   No biggy.

 

      a. Name: Initialize

      b. Script:

 

var identifier = context.name + '.' + activity.name;   // introducing just a bit more sophistication!

 

var incidentRecords = new GlideRecord('incident');

incidentRecords.addQuery('state', '!=', 7); // closed

incidentRecords.setLimit(workflow.inputs.u_numberofrecords); // note that this comes from your inputs

incidentRecords.orderByDesc('number');

incidentRecords.query();

 

var incident = {};

var incidentList = []; // this will be an array of objects

 

while (incidentRecords.next()) {

                      incident = {};

                      incident.sys_id = incidentRecords.sys_id + '';

                      incident.number = incidentRecords.number + '';

                      incident.assigned_to = incidentRecords.assigned_to.getDisplayValue() + '';

                      incident.short_description = incidentRecords.short_description + '';

                      incident.state = incidentRecords.state.getDisplayValue() + ''; // notice that we get the label

                      incidentList.push(incident);

}

 

workflow.scratchpad.count = incidentList.length - 1; // the overall count available

workflow.scratchpad.incidentList = incidentList; // the list of incident objects

workflow.scratchpad.counter = 0;   // our counter

workflow.scratchpad.message = '';   // the cumulative message

 

gs.info('---> [WF:{2}] Total number of records to loop: {0}, test value {1}', workflow.scratchpad.count, workflow.scratchpad.incidentList[workflow.scratchpad.counter].number, identifier);

     

 

c. Click the Submit button to create the Activity

 

5. Drag out a Run Script Activity on to the desktop.

 

a. Name: Compile Message

b. Script:

 

Here we will save up a cumulative message which we will print out each time to the System Log (in the Do Work Script Activity). Note that we are reference the "current" incident record using our object array, and our counter.   This is part of the magic!

 

var incident = workflow.scratchpad.incidentList[workflow.scratchpad.counter];

 

workflow.scratchpad.message += '[' + workflow.scratchpad.counter + ']'

                      + ' Number: ' + incident.number

                      + ' - ' + incident.short_description

                      + ' - ' + incident.assigned_to

                      + ' - ' + incident.state

                      + '\n';

     

 

c. Click the Submit button to create the Activity

 

6. On the Workflow Core tab, navigate to Timers

 

7. Drag out a Timer Activity.

 

        Here we will wait one second so that the logs are written down in order.   Otherwise there is no need for this activity.

 

a. Name: Wait a Sec

b. Timer Based On: A user specified duration

c. Duration: 1 seconds

d. Click on the Submit button to create the Activity

 

8. Copy the Wait a Sec Activity (we will need two for our workflow).

 

9. On the Workflow Core tab, navigate to Utilities

 

10. Drag out a Script Activity on to the desktop.

 

a. Name: Do Work

b. Script:

 

var identifier = context.name + '.' + activity.name;  

 

gs.info('---> [WF:{2}]\nLoop Count: {0} - Message so far:\n{1}', workflow.scratchpad.counter, workflow.scratchpad.message, identifier);  

     

 

11. On the Workflow Core tab, navigate to Utilities.   You will now see your new Turnstile (Enhanced) activity present in the list!

 

12. Drag out a Turnstile (Enhanced) Activity on to the desktop.

 

We can now enter a variable instead of an integer! Cool huh?!

 

            a. Name: Loop Check

            b. Allowed Iterations:   ${workflow.scratchpad.count}

            c. Click the Submit button to create the Activity

 

13. On the Workflow Core tab, navigate to Utilities

 

14. Drag out a Run Script Activity on to the desktop.

 

Here we will log down the final Message to the System Logs.

 

a. Name: Log Message

b. Script:

 

var identifier = context.name + '.' + activity.name;

 

gs.info('---> [WF:{1}]\nFINAL Message:\n{0}', workflow.scratchpad.message, identifier);

     

 

c. Click the Submit button to create the Activity

 

15. Wire everything up to look like the following:

 

image

 

16. Click on the triple bar in the upper left of the Desktop, then click on Edit Inputs. We will use this to define a single test input variable for our workflow.

 

17. Add a new input variable:

 

a. Name: Number of Records

b. Column Name:     u_numberofrecords
c. Type: Integer
d. Order: 100
e. Length: 40
f. Default Value: 5

g. Click the Submit button to create the new variable.

 

16. Close the Workflow Inputs form.

 

Now we are ready to test our new Turnstile Activity!

 

 

Testing

 

1. Now click the Run Workflow button on the top right. The Start Workflow form will appear.

 

2. Click the Start button to run the workflow.

 

image

 

3. Accept the default of five loops.

 

4. The workflow will loop through five times and then exit.

 

image

 

5. From your ServiceNow browser tab Navigate to System Logs → All. This will open the System Logs list view.

 

6. Filter for all messages starting with --->

 

7. Order by date Created descending.   You should see something like the following. There should be five entries showing the counting up from zero to four, then a "FINAL" message should be printed out with all of the entries.

 

image

 

Please mark my answer correct and helpful, If this will helps you in any way thanks in advance

Saurabh

Priyanka Vasant
Tera Guru

Hi Shaik,

The Turnstile activity limits how many times a workflow can pass through the same point.

When Working with large workflows,there might be a scenario where a workflow passes from same activity multiple times.The turnstile activity can be used in such scenarios to limit the number of times a workflow can pass though the same point.

Mark helpful or correct based on impact.

 

Reagrds,

Priyanka A.

VaranAwesomenow
Mega Sage

A very specific usecase can be, if you are waiting for a time based event to happen, but you dont want to wait forever cos it is possible tat that event may not occur or the condition used to identify that event is having issue because of which that event appears to have not occured, in that case workflow will try to go into infinite loop( to be precise would run more than number of allowed activity transitions configured as part of system property generally it is 100), when that happens workflow remains as an active transaction blocking a node thread which should be avoided from a performance perspective, hence adding turnstile would help in ensuring that workflow wont run for ever.

It can also be used in various other scenarios where requirement is to just run for a specific number of iterations.

If you need a similar functionality in flow designer, I found this article helpful
https://www.servicenow.com/community/now-platform-articles/creating-a-counter-or-turnstile-for-flow-...