When a task executes, it starts from nothing and performs commands until it completes. The notion that it "starts from nothing" is the one we want to examine. This means that when a new task comes into existence there is no pre-existing state in its initial working set. This does not mean that we can't make our own state, and have it persisted. For example, imagine we have a task that runs periodically and needs to process files that have arrived since the last time the task was run. If all we have is a directory of files, then we need to remember which files have previously been worked upon so that we can process only the new ones. To achieve this, we need to be able to save state from the last execution of a task and retrieve that saved state at the start of the next execution. There are many ways that state can be persisted. For example, we can use the services of a database. In this example, we will use a simple file on the file system. When a task ends, it will write its state as the content of a file. When a new task starts, it will read the file to retrieve its previous state. The next question before us is what should be contained within the file? In Automation Anywhere, we work with simple/unstructured variables and we are likely going to want to save and restore some set of these. Since Automation Anywhere has native support for XML based documents, it makes sense that we would use that technology.
Let us imagine we have a variable called "var1". Let us save this at the end of task and subsequently retrieve it.
The high level of the task is as follows:
In narrative, we read an XML document from a file on the local file system. This step also parses the document and builds an in-memory model of the data from which we can use XPath to retrieve the values. These are then assigned to variables that exist within the context of the task. In the middle we have now retrieved the state and can perform any/all processing we need. At the end, we re-write the XML document updating the content with the values for the variables.
In this example, we don't perform any error handling and in a production or more robust solution you may want to address that. For example, the solution as presented here assumes that there is an initial existing XML file containing the expected elements. If those don't exist, the task will fail. We could bracket the processing of the XML data at the start with an error handler to either create a new XML file and then read it or set the variables to default values.
Note the use of two session names ("Session1" and "Session2"). Despite having opened and then closed Session1, it was found that we couldn't create a second session also called Session1 despite the apparent fact that Session1 no longer existed. It appears that session names have to be globally unique even after a previous session has been completed.
The following video illustrates the story described above: