5

I have a custom timer job which is scheduled to run during specific time period.

I want to give a Run Now functionality using button click from custom sharepoint webpart. If i run timer job using a farm admin account using the code below everything works fine but any other sharepoint user with non farm account gets Access Denied issue.

var traceJob = (from jobDefinition in MainWebApp.JobDefinitions
                                where jobDefinition.DisplayName == "Sync Timer Job"
                                select jobDefinition).SingleOrDefault();
if (traceJob != null)
{
   traceJob.RunNow();
}

RunWithElevatedPrivilages neither impersonation was of any help. Can anyone help me please. How do i allow normal sharepoint users to execute the above code.

6

In order to execute RunNow method Farm Administrator rights are required. When you use RunWithElevatedPrivileges method, the code runs in the context of application pool account, which usually does not have farm admin rights (and it should not have it according to best practices)

So the solution is to run the code in context of some user that does have farm admin rights. I have not found nice solution to do it directly in the code for webpart, but it is possible to run it from another timer job (since timer jobs run with SharePoint Timer Service, which does have farm admin rights).

This is not very elegant solution, but you can create another timer job which is scheduled to run every minute. This timer job checks some kind of flag on your site, which is set when you click on that button in webpart. If the flag is set, then it runs your original timer job using RunNow method and resets the flag. You will have a delay between a button press and the actual timer job execution about a minute (sometimes less), which might be ok depending on what you are trying to achieve.

When you invoke RunNow method, the job is not executed right away, but it changes job definition and sets next run time to current moment in the database, so it will run next time the SharePoint Timer are processing timer jobs. There is typically a delay of 5-10 seconds anyway before the job is actually executed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.