Monday, 10 June 2013

Timer job in SharePoint 2010. How to create a timer job?

What is Timer Job in SharePoint - Timer Jobs are background processes that are managed by SharePoint. Timer job runs on a periodic basis defined in central admin.
Timer job runs periodically , can be scheduled hourly, daily, weekly.
Ex: User profile sync, Search Indexing


Timer job is a class which implements the SPJobDefinition class.
Timer job override the Execute method of SPJobDefinition class.


Timer Job Implementation and Code:

Follow below steps to implement Timer Job in SharePoint 2010.
Create a SharePoint Project in Visual Studio 2010.
Add a class in project.

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

        public MyTimerJob (string jobName, SPService service) :
            base(jobName, service, null, SPJobLockType.None)
        {
            this.Title = "Task Complete";
        }

        public MyTimerJob (string jobName, SPWebApplication webapp) :
            base(jobName, webapp, null, SPJobLockType.ContentDatabase)
        {
            this.Title = "Task Complete";
        }

        public override void Execute(Guid targetInstanceId)
        {
            SPWebApplication webApp = this.Parent as SPWebApplication;
            SPList taskList = webApp.Sites[0].RootWeb.Lists["Tasks"];
            SPListItem newTask = taskList.Items.Add();
            newTask["Title"] = "New Task Item" + DateTime.Now.ToString();
            newTask.Update();
        }
    }

Add a new feature.
Add event receiver to this feature.
Now write below code in Event Receiver Class.

const string JobName = "New Task Timer";
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPWebApplication web = (SPWebApplication)properties.Feature.Parent;
                    SPSite site = properties.Feature.Parent as SPSite;
                    DeleteExistingJob(JobName, web);
                    CreateJob(web);
                });
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


 private bool CreateJob(SPWebApplication site)
        {
            bool jobCreated = false;
            try
            {
                CustomTimerJob customJob = new CustomTimerJob(JobName, site);
                SPMinuteSchedule schedule = new SPMinuteSchedule();
                schedule.BeginSecond = 0;
                schedule.EndSecond = 59;
                schedule.Interval = 15;
                customJob.Schedule = schedule;

                customJob.Update();
            }
            catch (Exception)
            {
                return jobCreated;
            }
            return jobCreated;
        }

If you want , you may write code for feature deactivation.
From Feature property window, Select False in "Active on Default"
Define Feature scope to web application, so that it will not work for other web application.
Now you can deploy this to specific web application.
To activate this feature , go to central admin click on "Manage Web Application" under Application Management. Then on new page select your web application and click on Manage Feature from top ribbon. From the new opened popup you may activate your feature.

Then go to Monitoring->Timer Jobs and click on "Review Job Definitions"

Debugging timer job application is quite different from debugging normal code.
To debug timer job application, you need to attach OWSTIMER.EXE process.

No comments:

Post a Comment