SharePoint custom timer job running multiple times


Recently, I have come across with a problem where users are receiving 18 duplicate notification mails. We surprised that why the timer job sending 18 duplicate mails. Then we have checked the job history in QA and noticed that my job is executing 18 times daily.

Again we went in to a big confusion. That is, why the job is executing multiple times and also why 18 times, why not less or more :)

After digging some time we found that my web application has 18 content databases and our job running for each and every content DB. Not only my job, the rest of the jobs also running for each and every content DB. I think the rest of the jobs are handled some thing at code level due to this they did not come across with similar issue.

Initially we thought there is some problem in QA server but later we found that it is our code problem.

When we create a job we will add following constructors in our class file.
public PCTNotificationJob()
            : base()
        {
        }

        public PCTNotificationJob(string jobName, SPService service,
               SPServer server, SPJobLockType lockType)
            : base(jobName, service, server, lockType)
        {
        }

        public PCTNotificationJob(string jobName, SPWebApplication webapp)
            : base(jobName, webapp, null, SPJobLockType.Job)
        {
            this.Title = "PCT Notification Job";
        }

In the above constructor job lock type is very important. Earlier we have used SPJobLockType.ContentDatabase. Due to this the job has ran for each and every content database. To avoid this and if you want to execute your job only once then you have to use SPJobLockType.Job.

One more useful information I would like to share regarding job that is getting Site URL. In most of the cases we require to find our application URL to perform some operations. For this you might have used different approaches. But I would like to share one best approach for this.
That is using Property Bag feature we can easily get our site URL.

In Feature activated event while registering our job add your site URL to properties collection as below.
job.Properties.Add("PCTSiteUrl", site.Url);

then inside Execute method you can access this as below.
this.Properties["PCTSiteUrl"].ToString()


Comments

Post a Comment

Popular posts from this blog

Switch from Classic to Claims Authentication in SharePoint 2010

How to query list data using web service