SharePoint Learning
Login
Signup Free
User Login
Close
 
 
Keep me logged in on this computer
Signup for a FREE user account
Close
Email
Password
Designation (optional)
First Name
Last Name
Headline (optional)
Online SharePoint training videos and articles
Price: FREE

Create a SharePoint Timer Job in Visual Studio 2010

By Lin Zhang on 06 June 14

This article shows you how to programmatically create a SharePoint timer job (scheduled job) in Visual Studio 2010

1. Open Visual Studio 2010 and create a new project, select "Empty SharePoint Project", give it a name and click OK.
2. Deploy as a farm solution;
3. Right click "Features" in the Solution Explorer and "Add Feature". Change the Scope to "WebApplication".
4. Right click "Feature1.feature" and "Add Event Receiver".

Sample code in the main function:

const string List_JOB_NAME = "Agreement Task Reminder";

public override void FeatureActivated(SPFeatureReceiverProperties properties)

{

try

{

    SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;

    foreach (SPJobDefinition job in webApp.JobDefinitions)

{

if (job.Name == List_JOB_NAME)

{

    job.Delete();

}

}

TaskTimberJob listLoggerJob = new TaskTimberJob(List_JOB_NAME, webApp);

// run on Monday every week between 7:25:00 am to 7:25:59 am, use SPWeeklySchedule

SPWeeklySchedule weeklySchedule = new SPWeeklySchedule();

weeklySchedule.BeginDayOfWeek = DayOfWeek.Monday;

weeklySchedule.BeginHour = 7;

weeklySchedule.BeginMinute = 25;

weeklySchedule.BeginSecond = 0;

weeklySchedule.EndSecond = 59;

weeklySchedule.EndMinute = 25;

weeklySchedule.EndHour = 7;

weeklySchedule.EndDayOfWeek = DayOfWeek.Monday;

listLoggerJob.Schedule = weeklySchedule;

listLoggerJob.Update();

/*

SPMinuteSchedule schedule = new SPMinuteSchedule();

schedule.BeginSecond = 0;

schedule.EndSecond = 59;

schedule.Interval = 3;

listLoggerJob.Schedule = schedule;

listLoggerJob.Update();

*/

}

catch (Exception)

{

throw new SPException("Error obtaining refrence to the Web application.");

}

}

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)

{

SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;

foreach (SPJobDefinition job in webApp.JobDefinitions)

{

if (job.Name == List_JOB_NAME)

{

      job.Delete();

}

}

}

5. Right click the solution and "Add >> Class", name is "TaskTimberJob.cs".
Sample code in TaskTimerJob.cs: 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using Microsoft.SharePoint;

using Microsoft.SharePoint.Administration;

namespace TimerJob_Agreement_Task_Reminder

{

    class TaskTimberJob : SPJobDefinition

    {

        public TaskTimberJob()

            : base()

        {

        }

        public TaskTimberJob(string jobName, SPService service, SPServer server, SPJobLockType targetType)

            : base(jobName, service, server, targetType)

        {

        }

        public TaskTimberJob(string jobName, SPWebApplication webApplication)

            : base(jobName, webApplication, null, SPJobLockType.ContentDatabase)

        {

            this.Title = "A Timer Job - Agreement Task Reminder"; // appears in "Job Definitions" and "Scheduled Jobs" etc.

        }

        public override void Execute(Guid contentDbId)

        {

            /**********************************************************/

            /******************  Important  ***************************/

            //  Need to go to "Services" and restart 

            //  "SharePoint 2010 Timer" service for the changes 

            //  to take effect

            /**********************************************************/

            /**********************************************************/

            try

            {

                // get a reference to the current site collection's content database

                SPWebApplication webApplication = this.Parent as SPWebApplication;

                SPContentDatabase contentDb = webApplication.ContentDatabases[contentDbId];

                // get a reference to the "ListTimerJob" list in the RootWeb of the first site collection in the content database            

                SPList Listjob = contentDb.Sites[0].RootWeb.Lists["ListTimerJob"];

                SPList List_Recepients = contentDb.Sites[0].RootWeb.Webs["Departments"].Webs["admin"].Lists["Task Reminder"];

                SPListItemCollection listItems = List_Recepients.Items;

                foreach (SPListItem item in listItems)

                {

                    string name = Convert.ToString(item["Title"]);

                    string email = Convert.ToString(item["Email"]);

                    try

                    {

                        Uri address = new Uri("http://yourSharepointSite/Departments/admin/SitePages/Active%20Tasks.aspx?user=" + name   "&userEmail="   email   "&emailReminder=1");

                        System.Net.WebRequest request = System.Net.WebRequest.Create(address);

                        request.Credentials = System.Net.CredentialCache.DefaultCredentials;

                        request.Method = "GET";

                        System.Net.WebResponse response = request.GetResponse();

                        response.Close();

                    }

                    catch (Exception)

                    {

                    }

                    string receiveSecurityEmail = Convert.ToString(item["receiveSecurityEmail"]);

                    if (receiveSecurityEmail != "0")

                    {

                        string receiveAllNotifications = "";

                        if (receiveSecurityEmail == "2")

                        {

                            receiveAllNotifications = "&receiveAllNotifications=1";

                        }                    

                        Uri address = new Uri("http://yourSharepointSite/Departments/admin/SitePages/OutstandingSecurityAgreements.aspx?user="   name   "&userEmail="   email   "&emailReminder=1" receiveAllNotifications);

                        System.Net.WebRequest request = System.Net.WebRequest.Create(address);

                        request.Credentials = System.Net.CredentialCache.DefaultCredentials;

                        request.Method = "GET";

                        System.Net.WebResponse response = request.GetResponse();

                        response.Close();

                    }

                }

            }

            catch (Exception)

            {

            }        

        }

    }

}

 

Remember to restart the "SharePoint 2010 Timer" service for the changes to take effect.

Comments:

No comments.

Copyright © SharePointLearning.net.au. All Rights Reserved | Contact Us

Powered by DigiLife Studio