TL;DR; SPPersistedObject is a usefull class that can be used to store parameters for SPTimerJob in SPFarm.
Timer Job is a very useful service available in SharePoint. You can set a function which will be executed on the specific time. This scenario is useful in many SharePoint applications. It’s just like running SQL server job.
When working with the timer jobs, there is a little problem with parameters from the external source. Timer job doesn’t store passed parameters. In scenario, I have encountered in my job, there was a feature which was activating the TimerJob. On Feature parameters needed for the timer job were de-serialized from the xml file, then they were passed to the timer job constructor. When executed timer job was returning the default values, not the values from the xml file.
I started looking for a solution, and found the SPPersistedObject class which gives us the ability to remember the parameters in SPFarm.
The SPPersistedObject class provides a base class for all administration objects. It serializes all fields marked with the Persisted attribute to XML and writes the XML blob to the configuration database. The SPPersistedObject class contains code to serialize all its members that are base types, other persisted objects, and collections of persisted objects. Configuration data that is stored in persisted objects is automatically made available to every process on every server in the farm.
Let’s assume we have a scenario with a feature activating our timer jobs. We need to fill it with various parameters. To activate the timer job, we are using the feature receiver class, and feature activate method. First of all, we need to get our parameters to the feature receiver. I am using the serialized settings’ class and an xml file. Parameters from the xml are then used to create the SPPersitedObject. Base class is doing all the work with de-serialization and serialization of data. I only had to call the proper function before job execution to get the parameters.
How to use the SPPersistedObject
First of all, we have to create our class with parameters. It has to extend the SPPersistedObject. Every field we want to be “persisted” should be marked by a [Persisted] attribute. We have to create the properties explicit because only fields can be marked with this Attribute after creating this class all you have to do is to create the object fill it with parameters and then save it to the SPFarm.
With this simple class, the first step is to create the Persisted Object on the SPFarm. It is really important to call the Update() method.
The object is serialized. Now while executing the Timer Job all we have to do is to get the parameters from the SPFarm.
That’s all. Hope this will help someone in his work. Have fun with Timer Jobs.