Wednesday, March 26, 2014

How to create simple custom SharePoint timer job

Hi,

Few things to create a custom timer job.

1. Create a Feature
2. Create a .cs file and inherit SPJobDefinition and write custom code there.

The SP Feature Code Behind:

You can change the GUID here if it exists already or creates any issue...
[Guid("6ecf1f21-11fa-4109-baf7-0099347b5031")]    public class Entropic_Top_Blog_PostsEventReceiver : SPFeatureReceiver    {        // Uncomment the method below to handle the event raised after a feature has been activated.         public override void FeatureActivated(SPFeatureReceiverProperties properties)        {            SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;             // make sure the job isn't already registered            foreach (SPJobDefinition job in webApp.JobDefinitions)            {                if (job.Name == "Most Recent Blog Posts")                    job.Delete();            }            // install the job            MostRecentBlogPosts userSyncTimerJob = new MostRecentBlogPosts("Most Recent Blog Posts", webApp);            userSyncTimerJob.Schedule = SPSchedule.FromString("every 15 minutes");            userSyncTimerJob.Update();        }          // Uncomment the method below to handle the event raised before a feature is deactivated.         public override void FeatureDeactivating(SPFeatureReceiverProperties properties)        {            SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;            foreach (SPJobDefinition job in webApp.JobDefinitions)            {                if (job.Name == "Most Recent Blog Posts")                    job.Delete();            }        }          // Uncomment the method below to handle the event raised after a feature has been installed.         //public override void FeatureInstalled(SPFeatureReceiverProperties properties)        //{        //}          // Uncomment the method below to handle the event raised before a feature is uninstalled.         //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)        //{        //}         // Uncomment the method below to handle the event raised when a feature is upgrading.         //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)        //{        //}    } 


The .cs file Code Behind:

class MostRecentBlogPosts : SPJobDefinition
    {
        public MostRecentBlogPosts() : base() { }

        public MostRecentBlogPosts(string jobName, SPWebApplication webApp)
            : base(jobName, webApp, null, SPJobLockType.Job)
        {
            this.Title = jobName;
        }

        public override void Execute(Guid targetInstanceId)
        {
            return "Hello";
        }
    }
  

No comments:

Post a Comment