SP2013 TimerJob constructor SPServer parameter

246 views Asked by At

I have a timer job and I am trying to run this timer job on specific server, below is the code I am trying to use to compare server name and creating instance of timer job on FeatureActivated event. I have no idea how to do this. Please help me and correct me if I am doing it totally wrong.

public override void FeatureActivated(SPFeatureReceiverProperties properties)
    {
        // Get an instance of the SharePoint farm.
        //SPFarm farm = SPFarm.Local;

        SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;

        // Remove job if it exists.
        DeleteJobAndSettings(webApp);

        var serverName = SPServer.Local.DisplayName;
        if (string.Equals("sp2013", serverName, StringComparison.OrdinalIgnoreCase))
        {
            // Create the job.
            MyReportNew job = new MyReportNew(webApp, SPServer.Local);

           //Other code
        }
    }
1

There are 1 answers

1
tinamou On BEST ANSWER

Firstly, you need to use SPServerJobDefinition class.

Secondly, retrieve SPServer object from SPFarm.Local.Servers collection.

For example:

public class CustomJob : SPServerJobDefinition
{
    public CustomJob()
        : base()
    {
    }

    public CustomJob(string jobName, SPServer server)
        : base(jobName, server)
    {
        this.Title = jobName;
    }

    public override void Execute(SPJobState state)
    {
        // do stuff
    }
}

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
    // Get an instance of the SharePoint farm.
    SPFarm farm = SPFarm.Local;

    // Remove job if it exists.
    DeleteJobAndSettings(webApp);

    // Create the job.
    MyReportNew job = new MyReportNew("MyJobName", farm.Servers["sp2013"]);

   //Other code
}