sharepointtimer-jobssplist

How to access a list in a website from a timer job


I'm creating a timer Job. And i have to access some lists which are in my solution stored in the site : "http://server:9090/sites/thesite"

For the moment, in my Timer Job i use this :

 SPWebApplication webApplication = this.Parent as SPWebApplication;
 SPContentDatabase contentDb = webApplication.ContentDatabases[contentDbId];

 SPList ParametresTech = contentDb.Sites["sites/thesite"].RootWeb.Lists[Constantes.Listes.PARAMETRES_TECHNIQUES.Name];

The problem i'm facing here is that i'm in my development environnement, and i don't know what will be the url of the site they will use to deploy the solution in production.

So is there a way to get to the list without knowing the name of the site ?

Thanks

EDIT : That's how the timer job is activated :

public override void FeatureActivated(SPFeatureReceiverProperties properties)
    {
        string ListJobName = "SAPToSQL";


        SPSite site = properties.Feature.Parent as SPSite;
        // make sure the job isn't already registered
        foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
        {
            if (job.Name == ListJobName)
                job.Delete();
        }
        // install the job
        TimerJobSAPToSP listLoggerJob = new TimerJobSAPToSP(ListJobName, site.WebApplication);
        SPHourlySchedule schedule = new SPHourlySchedule();
        schedule.BeginMinute = 0;
        schedule.EndMinute = 59;
        listLoggerJob.Schedule = schedule;
        listLoggerJob.Update();
    }

Solution

  • I would definitely identify the site collection using the feature ID that creates the timer job rather than by URL. Not only does this give you flexibility in naming sites, it also allows you to process multiple site collections that have each subscribed to the job.

    I wrote the following utility method to collect the site collections for a timer job:

    public static List<Guid> GetSiteIDs(SPWebApplication webApplication, Guid featureId)
    {
        List<Guid> ids = new List<Guid>();
        foreach (SPSite site in webApplication.Sites)
        {
            try
            {
                if (SPSite.Exists(new Uri(site.Url)) 
                    && null != site.Features[featureId])
                {
                    try
                    {
                        ids.Add(site.ID);
                    }
                    catch (Exception ex)
                    {
                        // Handle Exception
                    }
                }
            }
            finally
            {
                site.Dispose();
            }
        }
        return ids;
    }
    

    In the featureId parameter, I pass a constant that I declare in my job definition class.

    For more information see: Scope of a feature activated Custom Sharepoint-Timer Job