Andrew Connell [MVP MOSS]
1543 Posts |  42 Articles |  4748 Comments
.NET  |  MCMS  |  SharePoint  |  Office System
SharePoint Quick Links
Article Categories
Archives
Post Categories


Add to Technorati Favorites

A few weeks back I posted about how you can create custom timer jobs for use in the latest release of SharePoint to perform scheduled tasks. However, considering there have been almost 40 comments to the post in the last three weeks, I figured the post needed some clarification (duh, ya think?).

The first thing you need to do is create a class that inherits from the Microsoft.SharePoint.Administration.SPJobDefinition class. To implement this class, you need to create a few constructors and override the Execute() method, like so:

   1:  namespace AndrewConnell.TaskLogger {
   2:    public class TaskLoggerJob : SPJobDefinition{
   3:   
   4:      public TaskLoggerJob ()
   5:        : base(){
   6:      }
   7:   
   8:      public TaskLoggerJob (string jobName, SPService service, SPServer server, SPJobLockType targetType)
   9:        : base (jobName, service, server, targetType) {
  10:      }
  11:   
  12:      public TaskLoggerJob (string jobName, SPWebApplication webApplication)
  13:        : base (jobName, webApplication, null, SPJobLockType.ContentDatabase) {
  14:        this.Title = "Task Logger";
  15:      }
  16:   
  17:      public override void Execute (Guid contentDbId) {
  18:        // get a reference to the current site collection's content database
  19:        SPWebApplication webApplication = this.Parent as SPWebApplication;
  20:        SPContentDatabase contentDb = webApplication.ContentDatabases[contentDbId];
  21:   
  22:        // get a reference to the "Tasks" list in the RootWeb of the first site collection in the content database
  23:        SPList taskList = contentDb.Sites[0].RootWeb.Lists["Tasks"];
  24:   
  25:        // create a new task, set the Title to the current day/time, and update the item
  26:        SPListItem newTask = taskList.Items.Add();
  27:        newTask["Title"] = DateTime.Now.ToString();
  28:        newTask.Update();
  29:      }
  30:    }
  31:  }

As you can see, this job does nothing important but add a new item to a Task list every time it's executed. Now that you have the job built, you need to get it registered. Unfortunately the only way to do this is through code, but it sure would be one heck of a candidate for a custom STSADM command. Anyway, since we don't have that today, I like to use the feature activated & deactivated events to install/uninstall my custom jobs.

To do this, you have to create another class that inherits from the Microsoft.SharePoint.SPFeatureReceiver class and implement the FeatureActivated & FeatureDeactivated event handlers like so:

   1:  namespace AndrewConnell.TaskLogger {
   2:    class TaskLoggerJobInstaller : SPFeatureReceiver {
   3:      const string TASK_LOGGER_JOB_NAME = "TaskLogger";
   4:      public override void FeatureInstalled (SPFeatureReceiverProperties properties) {
   5:      }
   6:   
   7:      public override void FeatureUninstalling (SPFeatureReceiverProperties properties) {
   8:      }
   9:   
  10:      public override void FeatureActivated (SPFeatureReceiverProperties properties) {
  11:        SPSite site = properties.Feature.Parent as SPSite;
  12:   
  13:        // make sure the job isn't already registered
  14:        foreach (SPJobDefinition job in site.WebApplication.JobDefinitions) {
  15:          if (job.Name == TASK_LOGGER_JOB_NAME)
  16:            job.Delete();
  17:        }
  18:   
  19:        // install the job
  20:        TaskLoggerJob taskLoggerJob = new TaskLoggerJob(TASK_LOGGER_JOB_NAME, site.WebApplication);
  21:   
  22:        SPMinuteSchedule schedule = new SPMinuteSchedule();
  23:        schedule.BeginSecond = 0;
  24:        schedule.EndSecond = 59;
  25:        schedule.Interval = 5;
  26:        taskLoggerJob.Schedule = schedule;
  27:   
  28:        taskLoggerJob.Update();
  29:      }
  30:   
  31:      public override void FeatureDeactivating (SPFeatureReceiverProperties properties) {
  32:        SPSite site = properties.Feature.Parent as SPSite;
  33:   
  34:        // delete the job
  35:        foreach (SPJobDefinition job in site.WebApplication.JobDefinitions) {
  36:          if (job.Name == TASK_LOGGER_JOB_NAME)
  37:            job.Delete();
  38:        }
  39:      }
  40:    }
  41:  }

Now... to get it working, all you need to do is:

  1. Deploy the strongly named assembly to the GAC.
  2. Reset IIS (required for SharePoint to "see" the new timer job in the GAC).
  3. Create a feature specifying the receiver class and assembly that contains the event receivers.
  4. Install the feature.
  5. Activate the feature.

This sample timer job assumes it's running within the context of a WSS v3 site that has a list created with the Tasks list template in the root web within the site collection (or, just create a Team Site at the root of your site collection).

Once you activate the feature, it should show up on the Timer Job Definitions page in Central Administration / Operations. It won't appear in the Timer Job Status page until it's executed at least one time. Wait for five minutes or so (the schedule this sample is using) to see if it's running. You should start to see items showing up in the Tasks list in the root site in your site collection.

Here's a Visual Studio 2005 solution that includes everything you need to create a custom timer job. Note that I used the technique I described in this article to modify the Visual Studio project to create the WSP file for me:

» TaskLogger_CustomTimerJob.zip

Or, you can use this Windows SharePoint Solution Package (*.WSP) to deploy the prebuilt timer job used in this article (handles steps 1-4 above):

» AndrewConnell.TaskLoggerJob.zip (unpack the ZIP to get the WSP)

To deploy the WSP file, simply add it to the solution store using STSADM (using the following command) and then deploy it to the desired site:

stsadm –o addsolution –filename AndrewConnell.TaskLoggerJob.wsp

Note: if you plan to test the timer job attached in that article, please make sure you also uninstall it. I just realized I never uninstalled mine and my Tasks list had over 30,000 items in it from the last few weeks. Oops! :)

[Update 7/2/2007 @ 11p] Make sure you don't use visible Features when deploying your custom timer jobs as explained here in this post. The two code downloads in this article have been updated to reflect as such.

[Update 4/8/2008 @ 12a] A Visual How-To I created on the subject of creating custom timer jobs was recently posted on MSDN. You can get more info here.

[Update 5/1/2008 @ 730a] There is now an in-depth article on MSDN about creating custom timer jobs. If you have trouble please check this out as there is a ton of additional info here. Post: More Help on Creating Custom Timer Jobs

posted on Thursday, February 01, 2007 10:47 PM

Feedback

# re: Creating Custom SharePoint Timer Jobs 2/2/2007 8:30 AM Vijay
Gravatar Finally! the code :)
Thanks so much

# re: Creating Custom SharePoint Timer Jobs 2/2/2007 9:33 AM Swati
Gravatar hi
1) I have deployed the wsp file and have activated the feature. But the feature is not visible in the Site Features. However, it is coming in the Timer Job Definition but after 5 minutes the task list is not populated

2)I have also checked the content database and there is no job shown in the schedule table(in content database)

Pls reply soon
Thanks in advance

# re: Creating Custom SharePoint Timer Jobs 2/2/2007 11:21 AM AC [MVP MCMS]
Gravatar Swati - Take a look at the feature that's deployed... it's not scoped at the Web, it's a site collection feature so you need to activate it from the Site Collection Features from Site Settings in the root web of your site collection. Also... stay out of the content database :)

# re: Creating Custom SharePoint Timer Jobs 2/3/2007 2:09 AM swati
Gravatar Hi
i have already activated the feature from the site collection features and when i try to activate the feature from site feature it give an error "Unknown Error " .
Pls Comment !!
thanx in advance


# re: Creating Custom SharePoint Timer Jobs 2/3/2007 5:16 AM Swati
Gravatar hi before you gave the whole code I had done very much the same thing except for 2 things-
1-I had the scope at Web level
2-I had Accessed the site directly and not referred the content Databse
and it was not loading the task list after 5 minutes of feature activation (was this the reason as to it not working?)

Also i hav deployed your wsp file and i had activated the Feature at sitecollection level still it wasnt visible in site feature

Pls help

Thanks:)

# re: Creating Custom SharePoint Timer Jobs 2/3/2007 10:43 PM AC [MVP MCMS]
Gravatar Swati - It will never be visitble in the Site Features page, because my sample demonstrates only the site collection level. Just change the feature to make it work for a web. The sample WSP does work, I just tested it again.

# re: Creating Custom SharePoint Timer Jobs 2/4/2007 7:44 PM Kanwal
Gravatar Thank you very much for the sample code Andrew.
I have posted a link to your article on my blog.

# re: Creating Custom SharePoint Timer Jobs 2/4/2007 11:44 PM Suja
Gravatar Andrew
Thnx for the new blog ...very much in detail..

Is it possible to read the Sharepoint appln 's web.config file inside my job. My requirement is tht the timer job should connect to a database and get some values to populate a specific SP list.
As per my understanding the job runs as a separate entity.
If possible can you give me some hints.

Thnx
Suja


# re: Creating Custom SharePoint Timer Jobs 2/5/2007 12:59 AM AC [MVP MCMS]
Gravatar Suja - Your job is getting kicked off by OWSTIMER.EXE, the executable for the WSS Timer Service (Windows service). It will not be running within the context of SharePoint, hence why it passes in a GUID for the content database which you use to get context of a specific site. You'll need to either figure out a way to get the web.config of your site (possible, as you can get a reference to the content DB, then the site collection, I'm sure the web application, which I'd expect would expose a property for the web root, where you can access the web.config. Whew.. that's a mouthfull... you've got some work ahead of you :). Or, you could just put the setting in the registry or somewhere else.

# re: Creating Custom SharePoint Timer Jobs 2/6/2007 5:40 AM Vijay
Gravatar Hi Andrew,

I was able to install the .wsp file using stsadm -o addsolution. I also did the deploy successfully using the Solution Management link. But now I am unable to activate it as the feature.xml file is not available! The ...Web Server Extensions\12\template\FEATURES location does not have a folder for this feature. I do not see this features in the Features list, not do I see it in the Timer Definitions screen.

Am I missing something?

Thanks,
Vijay

# re: Creating Custom SharePoint Timer Jobs 2/6/2007 5:53 AM Vijay
Gravatar Oops!! Spoke to soon! It's working like a charm :)

Thanks so much,
Vijay

# re: Creating Custom SharePoint Timer Jobs 2/9/2007 6:53 AM Donal
Gravatar Hi Andrew,

Thanks for the sample. I havent had a chance to play with this yet but one thing that confuses me is - how would you scope or paramaterize the job to run against a specific site collection. In your example the guid that gets passed to the Execute() is the guid of the content db - what I want also is the guid of the site collection the feature was activated on. Or would you use the base.Properties to store this.

Also are there any security implications in creating/deleting the job from the activation of a site collection feature.

Thanks

Donal

# re: Creating Custom SharePoint Timer Jobs 2/9/2007 8:52 AM AC [MVP MOSS]
Gravatar Donal-
Excellent question... you'll need to store this somewhere on your own. Best part: you can use the included property bag (SPJobDefinintion.Properties) to store your custom props.

Are there any security implications? Well, if it's a visible feature, then your site owners/site admins can add/remove timer jobs that are in assemblies in the GAC if the feature receiver adds it. The thing you want to be careful of though is if you don't want your site owners/admins doing this. In this case, I'd just make it a hidden feature that can only be activated/deactivated with server jockey via STSADM.EXE.

# re: Creating Custom SharePoint Timer Jobs 2/13/2007 7:55 AM Owe
Gravatar Hi,
Andrew.

Trying to deploy the example you supply to your article but having trouble getting the timer job going ...

Have successfully added the solution via Stsadmin (assembly is in GAC) and deployed globally in Central Administration. When I try to activate in Site Collection Features I get this "Unknown Error ". Looking into the application events tells me:

"Event Type: Error
Event Source: Windows SharePoint Services 3
Event Category: Database
Event ID: 5214
Date: 2007-02-13
Time: 13:45:51
User: N/A
Computer: WSS1
Description:
Insufficient SQL database permissions for user '' in database 'SharePoint_Config' on SQL Server instance 'WSS1'. Additional error information from SQL Server is included below.

EXECUTE permission denied on object 'proc_putObject', database 'SharePoint_Config', schema 'dbo'.

Do you have any suggestions on how to grant access to the database for the timer job assembly?

Thank you very much!

# re: Creating Custom SharePoint Timer Jobs 2/13/2007 8:53 AM AC [MVP MOSS]
Gravatar Owe - This indicates that the user account you're logged in under doesn't have admin rights to your SharePoint environment... make sure you are logging in with an account with admin rights to your SharePoint environment.

# Reading Web.config from timerjob. 2/16/2007 4:30 AM Ludwig
Gravatar To access the web.config from within a timerjob use the following code:

Configuration config = WebConfigurationManager.OpenWebConfiguration("/", "Sharepoint - 80");
string value = config.AppSettings.Settings["keyName"].value;

Have fun.




# re: Creating Custom SharePoint Timer Jobs 2/16/2007 7:42 AM Vijay
Gravatar Hi Andrew,

This might sound crazy, but I modified the code to
a. write to a different Task's list. But it just seems to ignore it.
b. I then removed the DateTime value and replaced it with a static value - this also did not work. I see the same datetime in the Title.
c. I then removed the insert and made it an update - this worked as expected - but it still continued to update the DateTime instead of the static value!

I ensured there were no mutliple copies of the .wsp, I also ensured the the DLL is getting deleted after uninstall and new version comes after install. I did a iisreset - but no change in behavior. This is driving me crazy!
Hope you can help!

Regards,
Vijay

# re: Creating Custom SharePoint Timer Jobs 2/16/2007 8:55 AM owe
Gravatar What admin rights is needed explicitly?

The user I am logged on (I am actually also logged on to the win server) is member of Builtin\Administrators group on the server, is set to Site Collection Administrator (for the site I try to activate the job for) and belongs to Site Owner group.

Also, the account has access to Sharepoint_Config database trough Builtin\Administrators which belong to DB Role: db_Owner.

Could there be some other setting I have to do?

Thanks.

# re: Creating Custom SharePoint Timer Jobs 2/16/2007 9:08 AM AC [MVP MOSS]
Gravatar Ludwig-
Thanks for posting that snippet for others.

Vijay-
I've seen this before... I had to keep incrementing the versions of the assembly when I was tweaking my code. I'm not sure if there is some caching going on, or if it's a bug... either way, I'll post back my results.

Owe-
That error is telling you that you don't have access to the config or content database. I don't remember what permissions you need offhand... check the Admin & Setup newsgroup.

# re: Creating Custom SharePoint Timer Jobs 2/16/2007 10:23 AM Gaetan
Gravatar many thanks for the post. Very clear and useful.

I have a windows app. which synchronizes users SP account with our users directory (using form auth. and a custom membership provider). I'm currently trying to replace this winddows app. with a SPJob (trying to do things the sharepoint way).

To be able to use all Membership related objects in my code, I added this portion in the app.Config file :

<system.web>
<authentication mode="Forms" />
<membership defaultProvider="AGDProvider">
<providers>
<clear />
<add name="AGDProvider"
connectionStringName="AGDProvider"
applicationName="MOSS2007 Membership Provider"
/>
</providers>
</membership>
</system.web>

you said the job was launched by the owstimer.exe.
So what file is owstimer.exe looking for when in thecode we use "ConfigurationManager.AppSettings[...]" ?

In what file should I put the membership configuration xml so that the job and owstimer.exe can use all Membership related objects ?

Gaetan.

# re: Creating Custom SharePoint Timer Jobs 2/19/2007 3:51 PM AC [MVP MOSS]
Gravatar Gaetan-
I suspect you'll need to add into your custom timer job to read from a specific configuration file... not adding it to some config file the OWSTIMER.EXE process is already reading from.

# re: Creating Custom SharePoint Timer Jobs 2/20/2007 10:10 AM Eric
Gravatar owe -
Try activating the feature from the stsadm tool rather than through the web interface. I was having the same permissions problem and this worked for me.

# re: Creating Custom SharePoint Timer Jobs 2/21/2007 7:28 AM Alex
Gravatar Hello.

Got a problem with Timer Jobs, can't resolve... I have my Job, that inherits SPJobDefinition, some constructors, overrided Execute(Guid targetInstanceId). I don't have feature, just register new job from inside a webpart. After registering it, I can see it in SP Central Administration, Last run time is changing just like it should according to the Schedule I pass to my job, but nothing happens. If I run Execute method from constructor, the things should happen are happen, no problems, so - no error in logic... but why don't they happen on schedule?

# re: Creating Custom SharePoint Timer Jobs 2/21/2007 8:17 AM AC [MVP MOSS]
Gravatar Alex-
Sounds like you either have a problem with the schedule or SharePoint isn't aware of it. Make sure you recycle the timer service, or even IIS... also make sure you give the job enough time to run. For example, I'd set a schedule for it to run every 2 minutes from 0-59 just to make sure its working.

# re: Creating Custom SharePoint Timer Jobs 2/23/2007 10:10 AM yongbo
Gravatar Hello, I made a TestTimer, an installer, and a feature. The Execute method just write a line to Event Log. I got an error: "TestTimer cannot be deserialized because it does not have a public default constructor" in the event log. But I do have default constructor, and three other constructor. My questions also include: 1) Do I need Manifest.xml? 2) Do I need all constructors as you have in your example? 3) I could not find Sharepoint Timer Service or OWSTimer.exe running, is that part of reason of failure?
Thanks.

# re: Creating Custom SharePoint Timer Jobs 2/23/2007 11:03 PM AC [MVP MOSS]
Gravatar Yongbo-
The error you describe is definately because the class doesn't contain a default public constructor. If you're sure your assembly has it, I'd suggest either (1) removing it from the timer job definitions, then incrementing the assembly version, then reinstall and test or (2) recycle IIS and the WSS Timer Service as I'm guessing the assembly is getting cached.

# re: Creating Custom SharePoint Timer Jobs 2/26/2007 10:12 AM Yongbo
Gravatar Thanks! Andrew, You are right that the assembly is cached, I thought it was removed when I iisreset and recycle application pool, but it was not. Maybe I did not do it properly. Finally after I restart the server, the problem is resolved. Thank you very much for your help. Can you give me hints on how to recycle IIS and WSS Timer Service?
Thank you again for your time.

# re: Creating Custom SharePoint Timer Jobs 2/26/2007 10:18 AM AC [MVP MOSS]
Gravatar Yongbo-
Resetting IIS won't do it, because the timer service runs outside of the web services... hence why when debugging you need to manually attach to the WSS timer service (OWSTIMER.EXE). To recucle that service, just open the Windows Services applet and recycle the service using the toolbar.

# re: Creating Custom SharePoint Timer Jobs 3/5/2007 11:12 AM Yongbo
Gravatar Thanks! The problem was: I have a timer job which runs a program deployed to GAC. After I change the program, deploy it to GAC, the timer job does not grab the updated one, instead, still runs the old one. I figured that the timer job has its own copy of the program and runs it every time triggered, instead of grabing it from GAC. That's why I need to restart the timer service. I actually resolved the problem by restarting the Window Sharepoint Timer Service.

Another problem I have now: The EndSecond of my SPMinuteSchedule is set to be 59, as you did in your example. I am not sure if this is the reason that the timer job stops executing after the one minute, even though the job is not finished. I want my timer job finish every time it's got triggered. Should I set EndSecond be more than 59?

I appreciate your time and reply!

# re: Creating Custom SharePoint Timer Jobs 3/5/2007 4:41 PM AC [MVP MOSS]
Gravatar Yongbo-
No... 59 indicates you want it to run up to the 59th second of every minute. Say for example you only wanted a job to run in the first quarter of every hour... you'd set the start time to 0 and the end time to 15.

# re: Creating Custom SharePoint Timer Jobs 3/6/2007 11:03 AM Yongbo
Gravatar Right. It's not a problem if the job takes less than one minute. What if the job needs more than 59 seconds, say 100 seconds, to finish, how do I set the schedule so that each time the job is started, it finishes no matter how long the job is going to take? I guess we might not be able to schedule a 2-minute timer job runs every 5 minutes. Thanks!

# re: Creating Custom SharePoint Timer Jobs 3/6/2007 4:30 PM Gary
Gravatar Andrew,

Great, detailed article. Also, I had the config database error trying to activate via the web interface, even though I'm logged in as an admin with rights to pretty much everything. But I was able to successfully activate via stsadm, and then the timer job worked like a charm.

Thanks Again!
Gary

# re: Creating Custom SharePoint Timer Jobs 3/21/2007 4:27 PM Michael
Gravatar Andrew,
Thank you for this post. The code works great and is exactly what I needed to get my job started. I am running in to a situation with the SPDailySchedule. Is there any information out there as to how to set that up?

I tried to set the .Begin/.End Hour, Minute, Second properties with 0/24, 0/59, 0/59 and set the NextOccurance property to DateTime.Now.AddMinutes(30). The first error I received was that the Datetime hour, minutes, seconds were not correct when I tried to activate the feature. So I removed them and left the NextOccurance property with the datetime value indicated above. It activated fine, but now I am not seeing that it executed.

Do you know where some information is on this schedule and how to set it up? I checked MSDN and it doesn't have much info other than the members of the class.

Thank you for any assistance in advance.

# re: Creating Custom SharePoint Timer Jobs 4/28/2007 7:00 AM Deenu Varghese
Gravatar This topic really helped. I didnt find any other documentation which explained the same.



# re: Creating Custom SharePoint Timer Jobs 5/1/2007 10:25 AM Matt
Gravatar Andrew,

I think I'm a little confused, I was able to downloaded your sample solution and build it with no problems, however I do not see my assembly in the GAC when I reset the IIS, or I dont see any reference to it int he features list or any other place taled about. Am I missing a deployment step other than just just bulding the process.

Any help is very much appreciated!!!

Matt

# re: Creating Custom SharePoint Timer Jobs 5/1/2007 10:41 AM AC [MVP MOSS]
Gravatar Matt-
You usually have to give it a bit of time... doesn't show up immediately. It has to run the first time for it to appear.

# re: Creating Custom SharePoint Timer Jobs 5/1/2007 11:21 AM Matt
Gravatar Well I was messing around with some things because I am not familar with accessing features throught the object model, anyways I added an install.bat tot he project which i used to deploy my workflows to the GAC. The .bat file calls the gacutil, and stsadm which deploys it to the GAC. This method allowed me to deploy it to the GAC correctly and I now see it in the timer job defintitons page on my SP central admin page. However when i log into the content database and try to locate the feature from the site features page under the admin tools, it does not appear, nor are any tasks getting created as of yet. Am I going about this the wrong way because I have been working on this for a couple hours now and nothing has worked shown up untill I added the install.bat.

Thanks a million for the quick response!!!
Matt

# re: Creating Custom SharePoint Timer Jobs 5/1/2007 8:55 PM AC [MVP MOSS]
Gravatar Matt-
The WSP should have certainly be deploying the assembly to the GAC... that's what you wantt o look at in terms of a solution. Creating a batch file to call GACUTIL is not a solution as it shouldn't be necessary. Not sure what's wrong... sorry.

# re: Creating Custom SharePoint Timer Jobs 5/2/2007 11:14 AM Matt
Gravatar Andrew,

Do you happen to run: "stsadm –o deploysolution –name <template_name>.wsp -allowgacdeployment" after you run the addsolution command. The add solution command alone never did anything, but once I ran the deploysolution command I was able to see it in the GAC. However even know I got it to deploy correctly it still is not functional. I wanted to mention that I am using WSS not MOSS, maybe that is a factor??? Lastly what did you use for your resurce for this topic, unfortunately this is the last functionality I needed in my project. I have bought and read both of the books you contributed to and niether addresses this problem.

Thanks,
Matt

# re: Creating Custom SharePoint Timer Jobs 5/2/2007 5:59 PM AC [MVP MOSS]
Gravatar Matt-
Well yes, you have to depoy the solution... adding it does nothing but add it to the solution store. Timer jobs aren't just a MOSS thing, they are a WSS thing. Unfortunatley there are hardly any resources for timer jobs. I've been meaning to augment the MSDN wiki SDK with some of my findings. There isn't anything in the books either... had to just use Lutz's Reflector and do some low level reflection and exploring of the object model to figure this out.

# re: Creating Custom SharePoint Timer Jobs 5/3/2007 3:57 PM Matt
Gravatar Andrew,

Thanks you very much for all your help, I'm finally starting to put all of the pieces together. I have a couple last questions, First is what is the actual deploy string you use to deploy your wsp? You can reference my last post for what i have so far, but you need to specify ether immediate, local or a time reference on the end of the string and I'm not sure what is the correct one. Second question is there any other steps neccessary to deploy the .wsp other than the correct stsadm deploy statement? Lastly, how do you deploy your solution when your in Visual Studios, do you just copy over the newly created .wsp file to the proper folder and then run the Addsolution and deploysolution commands accordingly?

Thanks again Andrew, I greatly look forward to any of your future posts!!!

Matt

# re: Creating Custom SharePoint Timer Jobs 5/3/2007 4:07 PM AC [MVP MOSS]
Gravatar Matt-
#1 - I typically don't deploy using the command line, I use the browser UI. Run STSADM.EXE -help deploysolution to get all the available switches or browse to Central Administration -> Operations -> Solution Management to deploy/retract/remove solutions (you can't add via the browser). For the command line, -local deploys it immediately (just like -immediate) or you can specify a time you want to schedule the deployment.

#2 - Nope... add the solution to the solution store and deploy. If you are deploying a feature, you'll probably have to go activate it. All a solution does is get the files to the appropriate spots on the server.

#3 - Today it's all manual copying files around. But if you look at the post, towards the end I link to an article on my blog showing how I build them in VS2005 with makecab.exe and MSBuild. In that article, I reference a post by Tony Bierman that takes it even futher, creating even more MSBuild target options for deployment. I suggest you read up on that.

More on #3 on my blog sometime in May (I hope... where's the time going?).

# re: Creating Custom SharePoint Timer Jobs 5/4/2007 3:59 PM Matt
Gravatar Andrew,

After fighting threw a number of problems I found out my problem was the Windows SharePoint Services Adminstration service was not started in services.msc. By default this services is not started on Windows Server 2003, I just wanted to post this to save others time over this silly issue.

Thanks a million for all of your help, I couldnt have gotten this far without it!!!

Matt

# re: Creating Custom SharePoint Timer Jobs 5/4/2007 5:18 PM AC [MVP MOSS]
Gravatar Matt-
There's an STSADM command called EXECADMSVCSJOBS that manually fires any queued jobs off... including the one you're trying to do in this case. This is useful if you don't want the service running (such as on a virtual machine).

# re: Creating Custom SharePoint Timer Jobs 5/6/2007 7:06 PM Chan
Gravatar HI Andrew,
I downloaded the your TaskLoggerJob wsp and tried to add it to the solution using stsadm, But I get the follwing error message

Object Reference not set to an instance of an object.

Do you know anything about this?
Any help is greatly appreciated.

Thanks
Chan

# re: Creating Custom SharePoint Timer Jobs 5/6/2007 9:05 PM AC [MVP MOSS]
Gravatar Chan-
Sorry, not enough info to troubleshoot.

# re: Creating Custom SharePoint Timer Jobs 5/7/2007 1:37 AM Chan
Gravatar Thanks ,

I fixed the problem !
The user i was logged onto the share point server didn't have dbo access to the sql server content and admin databases.

Thanks again
Chan

# re: Creating Custom SharePoint Timer Jobs 5/8/2007 11:46 PM Sathya Narayanan
Gravatar Hi Andrew,
Thanks for such a nice article!

I have tried the above code, but i am getting error. When i activate my feature and check in timer job status page of central admin, i can see the "Task Logger" installed with status "Failed". Any idea about this problem?

# re: Creating Custom SharePoint Timer Jobs 5/10/2007 2:27 PM Matt
Gravatar Andrew,

I'm sorry Andrew I just don't get what is triggering the Execute method, It doesnt seem to be inherently called anywhere in your code. I created my own job program that mimics your sample and it works fine, but when I start adding my custom code it seems to break it. Any information on how the method is actually getting called shaould be more than sufficient.

Thanks a bunch!

Matt

# re: Creating Custom SharePoint Timer Jobs 5/10/2007 2:36 PM Matt
Gravatar Duh I'm a retard, i just realized I removed the Override from the function definition for testing and forgot about it....

Sorry for wasting you space and time.

Matt


# re: Creating Custom SharePoint Timer Jobs 5/10/2007 6:53 PM Pankaj Sabnis
Gravatar I am looking at the SPDailySchedule class and have a question. I can schedule a timer job to run at a specified start and end time. But there is no way I can specify a date. Say I want a job to run from 1st June to 15th June at 1:00 am in the morning, how can I go about doing that. First of all, is it possible?

# re: Creating Custom SharePoint Timer Jobs 5/21/2007 7:42 PM calcock
Gravatar I've installed this with a scope="Farm". It shows up in the "Timer job definitions" list, but not in the "Timer job status" list as it never fires. Nothing in the event logs or the wss log files to indicate whether it tried to fire or not (got an error, failed in some way, etc.). Any suggestions on determining what the problem could be?

Tks.

# re: Creating Custom SharePoint Timer Jobs 5/30/2007 5:49 PM 7bergen
Gravatar Thank you for your article. Very helpful!

I have a really weird story; therefore I put it in here.

By activating the timer feature trough the user interface I receive a 404 access denied error. Also the feature page was not showing that the feature was activated; however, the timer job was activated in the 'background'. After some debugging I found out that it was file path permission issue, as per following error message:

Access to the path 'C:\Documents and Settings\All Users\Application Data\Microsoft\SharePoint\Config\bd189eb6-92d0-4ca5-87b0-770f542e3f0a\cache.ini' is denied.

Solution: If you give WSS_WPG user account full permission to the config folder (as per above file path) the error will disappear!

Is this not a weird situation? Are there any comments?

# re: Creating Custom SharePoint Timer Jobs 6/1/2007 9:52 AM Brian
Gravatar Nice article Andrew, but I got one question...

Do you have to create a wsp, file or can you install this as a feature? It seems like creating a wsp in quite the hassle compared to just installing a feature.

-Brian

# re: Creating Custom SharePoint Timer Jobs 6/1/2007 9:58 AM AC [MVP MOSS]
Gravatar Brian-
WSP's are just used for deployment... just like an MSI. You can install something manually, it's just easier using an installer. Yes, you can manually deploy the Feature, add the assembly to the GAC and activate the Feature. A hassel? I sure don't think it's a hassel.

# re: Creating Custom SharePoint Timer Jobs 6/1/2007 11:18 AM Brian
Gravatar Ah, ok I think I misunderstood at first. Thanks for the quick reply. So is the feature I install whatever class I have that inherits SPFeatureReceiver?

-Brian

# re: Creating Custom SharePoint Timer Jobs 6/1/2007 12:04 PM AC [MVP MOSS]
Gravatar Brian-
The Feature is simply a vehicle to install the timer job... this is done from code, which used the FeatureActivated event receiver to call this code.

# re: Creating Custom SharePoint Timer Jobs 6/21/2007 1:13 PM jayman
Gravatar Andrew,
Thank you for your article, it helps me a lot !
for sure, got a question for you : i have a web application containing 3 sites collections. 2 of them are on the same wss_content : wss_content1, and the last one is on another wss_content:wss_content2.
I expected the execute() method fire twice, because of the guid contentdb as a parameter, i scheduled the job once in a day. the job count items in document library and create a excel file and add it in another document library.
The problem is when i open the excel file, i only have the items count for wss_content1 the 2 first days, and the 3rd day i got the items count à wss_content2, the 4th day wss_content1 and the 5th day wss_content2.
Have you got a explaination for this ?
How can i do to have in the excel of a day, the count item of wss_content1 and the count item of wss_content2. any idea ?
thanks in advance.

# re: Creating Custom SharePoint Timer Jobs 6/24/2007 8:00 AM Renatas
Gravatar Hi,

nice article. I also had a problem the same as Alex. Job was registered and last run time correctly updated but job itself was not executed - that is "nothing happens".
So restarting OWSTIMER helps. After restarting the timer scheduled job executes fine.

# re: Creating Custom SharePoint Timer Jobs 6/25/2007 2:12 AM HV
Gravatar Thank you Andrew for such a nice post

I have a timer job feature.
I have used msbuild script to deploy/delete those features to farm.

I use the following commands in sequence to remove a solution (.wsp) from a site:

stsadm -o retractsolution -name Journaling.wsp -immediate
stsadm -o execadmsvcjobs
stsadm -o deletesolution -name Journaling.wsp -override
stsadm -o execadmsvcjobs

Retraction step works fine. But when it tries to delete the solution it says:

"The solution cannot be removed when a job is scheduled or running"

Though there are no such jobs running.

Any idea on why is it displaying such a message? Any solution to this?


# re: Creating Custom SharePoint Timer Jobs 6/26/2007 12:20 AM AC [MVP MOSS]
Gravatar HV-
Did you try refreshing IIS after the restraction? I wouldn't be surprised if the assembly was still in the cache.

# re: Creating Custom SharePoint Timer Jobs 7/13/2007 11:30 AM Yash Desai
Gravatar This article should go up in the Microsoft docs!

Thanks Andrew.

# re: Creating Custom SharePoint Timer Jobs 7/13/2007 3:28 PM Yash Desai
Gravatar Hi Andrew,

How would I have to set the Start and End times if I want the job to run at say 3pm everyday.

And can you explain it in detail?

thanks in advance.

# re: Creating Custom SharePoint Timer Jobs 7/16/2007 11:10 AM AC [MVP MOSS]
Gravatar Yash-
Just set the schedule to run between 3p-3:01p and run every minute.

# re: Creating Custom SharePoint Timer Jobs 7/17/2007 10:15 AM burnett
Gravatar hi,AC,this article is very useful to me.but i have a problem when i deploy this feature to the "Timer Job Definitions" for more than once.when i changed some feature in the class and build it to wsp file,when i deploy it to the server ,i find that the behavior doesnt change ,and the feature is the initial feature(the first time i deployed).
thoes bellow are all the commands i used.
============
stsadm -o retractsolution -name EventCheckTimer.wsp -immediate
stsadm.exe -o execadmsvcjobs
stsadm -o deletesolution -name EventCheckTimer.wsp -override
stsadm.exe -o execadmsvcjobs
stsadm -o addsolution -filename EventCheckTimer.wsp
stsadm -o deploysolution -name EventCheckTimer.wsp -immediate -allowgacdeployment -force
stsadm.exe -o execadmsvcjobs
======
i have tried out many ways .just as restart timer service, restart iis,even restart windows,but it seem to be helplessT_T

# re: Creating Custom SharePoint Timer Jobs 7/18/2007 8:33 AM AC [MVP MOSS]
Gravatar Burnett-
Check your caching... the assembly in the AC may not have been refreshed.

# re: Creating Custom SharePoint Timer Jobs 7/19/2007 2:12 PM Brad Merrell
Gravatar Andrew,

I have 2 custom timer jobs, which were installed using a installer applciations. They run at various times in the day. Last week, the front-end could not connect to the database dues to the database was being slammed with requests, so the database and front-end had to be restarted. When everything came back up all the "out-of-the-box" timer jobs start back to running, but the 2 custom timer jobs did not. I made sure the WSS Timer Service and WSS Administrion Server were running. These 2 timer jobs have been running on these server since December 2006, and we have rebooted all the servers in the farm a number of times since December, but something last week caused only the custom timer jobs to be executed. They show in the Central Administration > Operations > Timer Job Definitions, but never get run. I have uninstalled and reinstalled then, and nothing happens. Have you ever seen this happen before? Any ideas as to something that I have overlooked?

# re: Creating Custom SharePoint Timer Jobs 7/19/2007 11:50 PM AC [MVP MOSS]
Gravatar Brad-
No, first I've heard of that. Check the SharePoint logs? Any errors in the event log?

# re: Creating Custom SharePoint Timer Jobs 7/20/2007 9:32 AM mschoum
Gravatar I tried your code but when I activate the feature, the status of the timer job is on failed and stay on failed.
Is there someone who know the reason ?

# re: Creating Custom SharePoint Timer Jobs 7/20/2007 10:11 AM AC [MVP MOSS]
Gravatar Mschoum - What do the SharePoint logs say?

# re: Creating Custom SharePoint Timer Jobs 7/23/2007 7:25 AM mschoum
Gravatar Sorry,
There was a personal mistake in my Execute method !

# re: Creating Custom SharePoint Timer Jobs 7/23/2007 10:13 PM Amish
Gravatar Hi Andrew,
Thanks for such a great article. I was wondering what is the behaviour of the Execute method when the web application under which the Job is running have multiple database. I tried it on two different servers and the behaviour was different. In one case it got fired for all the Content DB that were part of the web application but in other environment it got fired for only DB. Any reasons why this could happen. Thanks in Advance.

Regards,
Amish

# re: Creating Custom SharePoint Timer Jobs 7/24/2007 8:20 AM AC [MVP MOSS]
Gravatar Amish-
Good question... not sure... guess you'd just have to test it.

# re: Creating Custom SharePoint Timer Jobs 7/24/2007 8:39 PM Leonwoo
Gravatar Andrew,
Great article. I am having a problem to figure out how to associate the timer with a particular user action. When a user added in a new item into a list, I would like to send an email out.
Is it possible to build a timer job in MS WorkFlow? How?

Thanks in advance.

-Leonwoo

# re: Creating Custom SharePoint Timer Jobs 7/25/2007 10:45 AM AC [MVP MOSS]
Gravatar Leonwoo-
Timer jobs aren't associated with users or kicked off on demand or by an event. They are only kicked off on a predefined schedule within the context of a site, site collection or web application. Timer jobs also can't live within workflows.

# re: Creating Custom SharePoint Timer Jobs 7/25/2007 10:45 AM AC [MVP MOSS]
Gravatar Leonwoo-
Timer jobs aren't associated with users or kicked off on demand or by an event. They are only kicked off on a predefined schedule within the context of a site, site collection or web application. Timer jobs also can't live within workflows.

# re: Creating Custom SharePoint Timer Jobs 7/27/2007 10:47 AM Yash Desai
Gravatar hey Andrew,

If I use the SPDailySchedule instead of the SPMinuteSchedule, how do I know how many times this will run the selected timeframe. If you notice, SPDailySchedule doesn't actually have an "interval" field like SPMinuteSchedule does...

any ideas?

For now I have the following. Not sure if this will work yet.
---------
SPDailySchedule runSchedule = new SPDailySchedule();
runSchedule.BeginHour = 15;
runSchedule.BeginMinute = 0;
runSchedule.BeginSecond = 0;

runSchedule.EndHour = 15;
runSchedule.EndMinute = 30;
runSchedule.EndSecond = 0;
taskLoggerJob.Schedule = runSchedule;

taskLoggerJob.Update();
--------

# re: Creating Custom SharePoint Timer Jobs 7/31/2007 11:03 AM Todd Friedlich
Gravatar Not sure if anyone updated this yet, but if you have a problem where your newly updated DLL in the GAC isn't being used by your timer job, incrementing the version or build number takes care of it. Huge pain, but it works.
todd

# re: Creating Custom SharePoint Timer Jobs 7/31/2007 1:52 PM AC [MVP MOSS]
Gravatar Todd-
That's likely because it's been cached. Recycle the timer service would fix this. Incrementing the version number is seen as a completely different assembly in the GAC so recycling the timer service fixes this.

# re: Creating Custom SharePoint Timer Jobs 7/31/2007 2:03 PM dcp
Gravatar Andrew,
Thanks for the post. I am having some trouble getting it working. I have the code compiled. I installed and activated the feature. I added in some code to write the the event log and GACed the dll. It is showing up in the Timer Definition list but it is never executing.

I tried to execute the wsp file you have for download with the same result. If I try to disable and enable the job I get an error in the log that says:
Job definition AndrewConnell.TaskLogger.TaskLoggerJob, id 16384a95-28e6-42a6-8a20-c86dcc453c67 has no online instance for service Microsoft.SharePoint.Administration.SPWebService, id 5c83f09a-7eaa-4280-8052-9524afe65828, ignoring

Any thoughts about what I might have done wrong?

thanks,
dcp


# re: Creating Custom SharePoint Timer Jobs 7/31/2007 2:12 PM AC [MVP MOSS]
Gravatar dcp-
Sorry... the code definately works as is. I've tested it numerous times on various virtual machines so I'm not sure what you're doing.

# re: Creating Custom SharePoint Timer Jobs 8/13/2007 6:53 AM mschoum
Gravatar I have the following error, nevertheless I have a list on the root of my site collection

Any ideas ?

08/13/2007 12:45:01.92 OWSTIMER.EXE (0x0824) 0x0F6C Windows SharePoint Services Timer 7psa Critical The Execute method of job definition SPUpdateListTimerJob.SpTimerJob (ID c8a64945-d233-46b8-9c5b-bd376e250ccc) threw an exception. More information is included below. List not foundFalse
08/13/2007 12:45:01.93 OWSTIMER.EXE (0x0824) 0x0F6C Windows SharePoint Services Timer 72ae Unexpected Exception stack trace: at SPUpdateListTimerJob.SpTimerJob.Execute(Guid contentDbId) at Microsoft.SharePoint.Administration.SPTimerJobInvoke.Invoke(TimerJobExecuteData& data, Int32& result)

# re: Creating Custom SharePoint Timer Jobs 8/13/2007 11:31 AM mschoum
Gravatar Is it possbile to debug the TaskLogger.execute() method ?
I can debug the feature events but not the TaskLogger.execute() one

When I attach the debug process I can break on the constructor, feature event but not on the execute method, even if the job is on succeeded !!

How can I debug this one ?

# re: Creating Custom SharePoint Timer Jobs 8/13/2007 12:58 PM AC [MVP MOSS]
Gravatar Mschoum - Attach to the timer service.

# re: Creating Custom SharePoint Timer Jobs 9/7/2007 7:53 AM Kalpesh
Gravatar FeatureInstalled
This event never fired? Is this bug?

# re: Creating Custom SharePoint Timer Jobs 9/7/2007 8:45 AM AC [MVP MOSS]
Gravatar Kalpesh-
They can take up to 15m to get kicked off.

# re: Creating Custom SharePoint Timer Jobs 9/13/2007 5:07 AM David Collis
Gravatar I have a few questions which so far I have not been able to find the answers to via excessive googling.

1. How do you deal with errors / exceptions in your code? Is there a specific sharepoint logger that we can write to.

2. If you need to persist a variable between multiple executions of the code (and even if sharepoint is restarted) then is there a simple place to store them?

3. What happens if a piece of code you use in the timer job requires there to be an app.config or web.config (i.e. it includes a dll that simply calls ConfigurationManager.AppSettings[&quot;variable&quot;]). Is there a sensible place to put these settings? OWSTimer.exe.config doesn't seem like a particularly clean solution.
Where will the timer job look on this call?

Hope someone can help...

p.s. Sorry if i submitted this multiple times, its just nothing seemed to happen when I pressed the submit button in Firefox.

# re: Creating Custom SharePoint Timer Jobs 9/13/2007 10:00 PM AC [MVP MOSS]
Gravatar David-
1 - You can write to the ULS, but it isn't terribly easy. Check the WSS SDK for code samples.
2 - What's the scope of the timer job? Web app / site collection / site? If so, stick it in the property bag for those objects.
3 - I wouldn't use a config file at all. If anything, I'd use a Feature to install / register the timer job. Use the properties of the Feature to pass in config stuff and save that config stuff in the property bag for the object it's scoped to (site collection).

# re: Creating Custom SharePoint Timer Jobs 9/14/2007 3:59 AM David Collis
Gravatar Andrew - thanks for your comments. Very helpful. I will look up the ULS as suggested, but am thinking that the event log might be a more sensible place for it now.
The propertybag was exactly what I was looking for! Seems so obvious now, why I didn't think of looking for a "properties" attribute I don't know.

Finally, I am using a feature to install and register the job, however I am not sure how to pass in config stuff to it.
My problem is that I need the config to be accessible via ConfigurationManager - i.e. the default file. For example, at the organisation where I currently work, we have a modified database application block (which must be used) which can only be used by putting settings in the app.config or web.config.
If I put the config in the properties of the feature, I don't think these config values would be available via the ConfigurationManager would they?

Sorry if these questions seem basic, I am new to sharepoint and haven't been programming in .NET for quite a while.

# re: Creating Custom SharePoint Timer Jobs 9/14/2007 7:57 AM AC [MVP MOSS]
Gravatar David-
Not familiar with the EntLib... I don't consider it a good idea to have a DLL with dependencies on another file for config stuff for many reasons, one being this. Maybe your app block can have that data passed in dyamically instead of reading from a config file.

# re: Creating Custom SharePoint Timer Jobs 9/14/2007 8:15 AM David Collis
Gravatar Andrew - I couldn't agree more, unfortunately this is what I am stuck with right now.
And unfortunately I believe one of the modifications to the block prevents the config from being read in another way.

Just out of interest, any idea where a TimerJob would try to look if you called ConfigurationManager.AppSettings in the code?

# re: Creating Custom SharePoint Timer Jobs 9/14/2007 8:32 AM AC [MVP MOSS]
Gravatar David-
Wild speculation would be the OWSTIMER.EXE.config file, but who knows. Use FileMon.

# re: Creating Custom SharePoint Timer Jobs 9/14/2007 8:45 AM David Collis
Gravatar Yep, fair enough. I'll post back here if I figure it out. Thanks for your help Andrew. Much appreciated.

# re: Creating Custom SharePoint Timer Jobs 9/17/2007 6:28 AM David Collis
Gravatar Just a quick follow-up.
Putting config in OWSTIMER.exe.config (that you have to create yourself in the same location as OWSTIMER.exe of course), works fine for application config. This appears to be the default location to read from.

I did run into a problem where nothing worked at all until I had restarted the "Windows SharePoint Services Timer" service however.

Cheers,

David

# re: Creating Custom SharePoint Timer Jobs 9/18/2007 4:34 PM bazztrap
Gravatar If we can read a list why can configuration xml or config file exist in a list. and read of the list which is at the root level.



# re: Creating Custom SharePoint Timer Jobs 9/19/2007 6:14 AM Neil Gilroy
Gravatar Hi, I used this excellent code to set up a SPJobDefinition. That works - i.e. I can create the job and it runs fine.

I managed to get SPJobDefinition.Execute() to work - and an Async call using a simple delegate.

However, I would like to let the user modifiy the schedule via the UI. Calling 'SPJobDefinition.Update()/SPJobDefinition.Update(true)' always gives me a SQL permissions error on proc_putObject on the config DB. The code runs as the app pool user - which is a domain admin in my setup but does not have execute permissions on this Stored Proc (SP). Although concerned, I gave him execute rights and then I got a filesystem permission error on a cache.ini file for the config DB. After I fixed this I got another SP permissions error etc etc. I dont feel comfortable making all these changes.

When I run SQL Profiler, the 'Configure Profile Import' screen which suports modifying the FULL and INCREMENTAL profile imports calls a totally different set of stored procs with better soundng names - 'proc_MIP_ModifyScheduledJob' etc. Thing is, using Reflector it seems this code is embedded in the webcontrol SPSJobScheduler which I cannot edit/make do what I want to do.

Im really getting stuck here... anyone run into this before?

Thanks,

Neil

# re: Creating Custom SharePoint Timer Jobs 9/19/2007 7:42 AM AC [MVP MOSS]
Gravatar Neil-
You shouldn't feel comfortable doing that stuff. First, having your app pool identity as a domain admin is not a good idea... that's WAY to permissive. You should not be adding more rights to your DB's in order to let your users change the schedule. One way is to save the schedule settings somewhere, then write a timer job that comes in and changes the schedule for you as it would have the permissions necessary to do this.

# re: Creating Custom SharePoint Timer Jobs 9/27/2007 9:44 AM Jay
Gravatar Andrew,

Great article. I have crteated a timer job thanks to this article. Now the problem is, how do I specify the schedule outside of the timer classes installer code, where you specify the schedule. The reason I asked for this is that I need to allow administrator to customize the schedule to run my timer job via a custom UI.

Thanks very much!

# re: Creating Custom SharePoint Timer Jobs 9/27/2007 9:50 AM AC [MVP MOSS]
Gravatar Jay-
That will require you creating some custom and pages within the admin that use the same code to reregister and change the schedule.

# re: Creating Custom SharePoint Timer Jobs 10/10/2007 8:14 AM Tudor
Gravatar Hello.

Do you know of any reason why a timer job would be executed multiple times, even though it is set to run hourly? The job does some computing and sends one summary e-mail. We always get three e-mails and, while the job is scheduled to run hourly, sometimes the occurences are only 10-15 minutes apart. Do you have any idea why would this happen?

Thank you

# re: Creating Custom SharePoint Timer Jobs 10/10/2007 8:40 AM AC [MVP MOSS]
Gravatar Tudor-
Sounds like it has been registered more than one time... check your timer jobs. One common mistake I see people make is not deleting the timer job when reregistering it.

# re: Creating Custom SharePoint Timer Jobs 10/10/2007 9:05 PM Brenda
Gravatar Andrew:

Are you aware of any issues with multiple WFEs in the MOSS farm where the timer job gets executed multiple times? I do have the code in place to delete the timer job if it already exists while the feature is activiating.

thanks.

# re: Creating Custom SharePoint Timer Jobs 10/11/2007 2:58 AM Tudor
Gravatar Hello Andrew,

Thank you for your reply. My timer job is a bit special in the sens e that when it is executed, it reads the scheduling parameters from a configuration file and then re-schedules itself. Upon this rescheduling, I can't remove the current instance (since it's being executed), but the changes on the current object are updated using the Provision() and Update(true) methods (the argument is "true" so that an exception will not be raised). When the job is initially deployed, any existing instances are deleted (although this happens only once).

When checking the timer job definition list in Central Administration, there is only one instance of my current job.

Also, this problem occurs on only one server, when testing on subsequent machines the job works fine, is being rescheduled and runs only once when it's up for execution. Could this be a configuration issue of some sort?

Thank you,
Tudor

# re: Creating Custom SharePoint Timer Jobs 10/12/2007 9:36 AM AC [MVP MOSS]
Gravatar Tudor-
I'm a little confused about your problem... sounds like you only have one job defined. I think your best bet is to create another timer job that does the scheduling of your primary job to achieve your goals.

# re: Creating Custom SharePoint Timer Jobs 10/22/2007 10:39 AM Peter
Gravatar Thanks for a greate article.

Is there a difference between timer jobs in MOS and Services?

I have succesfully installed the job on a vpc with sharepoint services. There it works fine. When I instal the same job on a MOS invirement (upgraded from beta) it installs fine, but the job is never fired. I write exceptions from my code to the log, but nothing shows there.

I can see the job in the job defenition, but the "last time run" is always "N/A".

I have done iis reset and reset the windows sharepoint timer services with no result. I also reinstaled the job with new version on the assembly, but nothing worked. I have tried execadmsvcjobs.

AI?

Only error I have in the logfile is:
Failed to find the XML file at location '12\Template\Features\PremiumRootSite\feature.xml'

but i dont now if it has someting to do with the job.

/David

# re: Creating Custom SharePoint Timer Jobs 10/22/2007 7:50 PM AC [MVP MOSS]
Gravatar David-
Timer jobs are WSS things... not MOSS things so it should work, but I'm not certain what's going on in your case. There might be a dependency issue in your code. Have you tried debugging it by attaching to the OWSTIMER.EXE process.

# re: Creating Custom SharePoint Timer Jobs 11/5/2007 5:12 AM Liza
Gravatar Hi Andrew,
we have set up at timer job similar to yours, only our job copies some files to the virtual directory. The job is started by a feature, activated on site level. It works fine - on the one server, where the feature is activated, but all other FE servers in the farm does not get updated. Any ideas?

/Liza

# re: Creating Custom SharePoint Timer Jobs 11/5/2007 7:13 PM Nathan
Gravatar Hi Andrew,

I’ve modified your code so that it copies resx files from the feature into the App_GlobalResources folder. It works fine on a single box; however it does not propagate those changes to all the web servers.

From my understanding SPJobDefinition should create a job on all front end servers in the farm when a web application calls an update method. Essentially I would like to copy the custom resx files into App_GlobalResources folder upon feature activation in a multi web-front-end environment.

Any help or hints will be much appreciated.

Cheers
nathan


# re: Creating Custom SharePoint Timer Jobs 11/7/2007 10:32 AM AC [MVP MOSS]
Gravatar Look at the SPJobDefinition.LockType property. When set to SPJobLockType.Job the job only runs on the server where it was submitted/scheduled. Otherwise if it is SPJobLockType.None, it runs on every server in the farm.

# re: Creating Custom SharePoint Timer Jobs 11/7/2007 10:53 AM Nathan
Gravatar Thanks for the prompt reply. That's what I have done last night and it worked.

Cheers
Nathan

# re: Creating Custom SharePoint Timer Jobs 11/15/2007 11:57 AM Rajesh Khatri
Gravatar Hi Andrew/David Collis,

This is regarding the question raised by David Collis (Reading config file) from SPTimer job.

I am facing the same issue and need to resolve it asap.

Could you please suggest how did you resolve it?

Thanks and regards,
Rajesh Khatri

# re: Creating Custom SharePoint Timer Jobs 11/15/2007 10:00 PM Joe
Gravatar Andrew,

Thanks for the article. Great stuff. After some mis-steps I have my timer job doing what it needs to.

I was having some problem deploying it, since I was developing and testing and making changes, I was just installing my DLL in the GAC and installing and activating the feature and resetting IIS.

I was getting the same problem some mentioned above with it not appearing to be executing my "Execute". Well, it was trying , it appears it was using an older copy of my DLL.

Restarting the Sharepoint Timer service seemed to be the trick to getting it use my newly deployed DLL.

Thanks again for this article.

# re: Creating Custom SharePoint Timer Jobs 11/19/2007 4:15 AM sai
Gravatar hi Andrew,
using this Custom sharepoint Timer jobs can i send mails like if i given the future date and stored in the splist and execure timer job daily and if the date is todays date then mail should send.

please give me reply.
Thanks in adavance,
sai


# re: Creating Custom SharePoint Timer Jobs 11/20/2007 2:15 PM AC [MVP MOSS]
Gravatar Sai-
Sure, you can definately do this. It's no different than creating a console app that runs at specified intervals and based on the last time it was run, does some work.

# re: Creating Custom SharePoint Timer Jobs 11/28/2007 2:36 PM Tom
Gravatar Andrew,
This looks like it would be perfect for sending notifications of impending or delayed tasks/events/open items. As Sai seems to have the same idea.

Do you know of anyone that has created such a job?

thanks.


# re: Creating Custom SharePoint Timer Jobs 11/29/2007 4:28 PM AC [MVP MOSS]
Gravatar Tom-
Not personally, but I'm sure someone has done this before. I'd suggest posting to the MSDN online forums: http://forums.microsoft.com/MSDN/ShowForum.aspx?ForumID=1203&SiteID=1

# re: Creating Custom SharePoint Timer Jobs 11/30/2007 10:30 AM Nick
Gravatar Hi Andy,

Great post - I also like your thoughts on the VS 2008 bloggers!

I've written my own SPJobDefinition following your example. I've been having problems deploying it to a farm evironment.

First I started with errors on some of the servers with &quot;cannont write to the 12 folder&quot; errors

Then I had problems with some of the servers unable to find the assembly.

These were fixed either by restarting the timer sevice or the server itself.

Now I deploy the solution but it's stuck in the &quot;deploying&quot; state.

Any ideas how to get round it?

Thanks,
Nick

# re: Creating Custom SharePoint Timer Jobs 11/30/2007 10:51 AM Amit
Gravatar Hi,

I am amit.We have developed a custom timer job.But i am facing problem in deploying this job to server environment.The deployment on single server happens perfectly on 1 server,but problem comes when we try to deploy this job in server farm environment.
We have two front end servers in our deployment environment.
I have installed the feature using cmd stsadm -o installfeature -filename DeletingEventHandler\feature.xml.By running this command feature got installed on server and when i activated the feature,timer job got created but it ran successfully only one of our front end servers,and not on both the front end servers.Any idea how it could be installed on other front end server.

# re: Creating Custom SharePoint Timer Jobs 11/30/2007 10:52 PM AC [MVP MOSS]
Gravatar Nick-
Check out the STSADM operation EXECADMSVCJOBS as it pushes any jobs that have been scheduled, but not deployed (solution deployment is done by a job so this will unclog the pipe to so speak).

Amit-
No way to know what the problem is without more info. You say it was deployed, but didn't run. What error did you get?

# re: Creating Custom SharePoint Timer Jobs 12/3/2007 3:48 AM Amit
Gravatar Hi Nick,

I am trying to update an xml file from timer job.As already told we have 2 frond end servers installed and central admin lies on another server.When i installed this timer job using stsadm,it said operation successful.
When i saw the status of this timer job in central admin,it showed that timer job ran successful on 1 of the servers.
I couldn't see the job in Job defination sections as well.

The above scenerio worked perfectly when we ran this with 1 front end configuration,but with 2 front end configuration,it ran successfully on only 1 of the servers.


Amit

# re: Creating Custom SharePoint Timer Jobs 12/12/2007 10:43 AM Laurent
Gravatar Hi Andrew,

Thanks for a great post and for answering all these questions.

I have a curious problem. I have used you code above to create a job. The job needed some configuration strings and I added the strings via the .Properties of the newly create job.

By accident I passed it the reference to an object which can not be deserialized. Of course the job can not run, because one of its properties can not be read in. The funny part is that I can not delete the job again. When I iterate through WebApplication.JobDefinitions, it seems to try and create an instance of the job in question and I get the following error:

The platform does not know how to deserialize an object of type System.Configuration.ConnectionStringSettings. The platform can deserialize primitive types such as strings, integers, and GUIDs; other SPPersistedObjects or SPAutoserializingObjects; or collections of any of the above. Consider redesigning your objects to store values in one of these supported formats, or contact your software vendor for support. at Microsoft.SharePoint.Administration.SPAutoSerializingObject.DeserializeBasicObject(XmlElement xmlValue) [...]

The same occurs when I try and retract the solution, the job is part of...

Do you know of any way to delete a JobDefinition, without it trying to instantiate the job?

Laurent

# re: Creating Custom SharePoint Timer Jobs 12/14/2007 3:38 PM sadrout
Gravatar Hi Andrew,

Thanks for this post.
I've tried your code.It works perfectly.
i did not have difficulty to deploy the solution and active the feature.
I have modify the Execute function to send an email.it works.
I have even changed the schedule of the job it works great.
But there is something that i don't understand.
I have modify the execution function to send emails.
I have modify the FeatureActivated function to run the job every 5 minutes,it works but the first execution of the job begins 10 minutes after the first launch of the job.
To be clear, the job runs 2 times without execut the code and it was in the third time that the code was executed for the first time.
After, the job runs normaly every 5 minutes normaly.
Can someone Have a explaination for this ?


# re: Creating Custom SharePoint Timer Jobs 12/17/2007 8:14 AM Laurent
Gravatar Hi again.

Just wanted to post that I had resolved the issue. I had to modify the SharePoint database to edit the .Properties associated with the job (I removed the offending property from the xml serialization of the properties).

The properties associated with the job resides in the database SharePoint_Config and in the table dbo.Objects. I located a row here with the column [Name] set to the same name as my SPJob. The column [Properties] contains the properties associated with the SPJob.

(The table dbo.TimerRunningJobs, contains a entry corresponding to the SPJob, but deleting this row did not remove the job).

Laurent

# re: Creating Custom SharePoint Timer Jobs 12/17/2007 10:57 AM Philipp Schumann
Gravatar Thanks for this. Instead of "myJob.Update();", what worked for me was

site.AllowUnsafeUpdates = site.RootWeb.AllowUnsafeUpdates = true; site.WebApplication.JobDefinitions.Add (myJob);

# re: Creating Custom SharePoint Timer Jobs 12/17/2007 9:36 PM AC [MVP MOSS]
Gravatar Laurent-
This is absolutely *not* the way you should fix it. Never go into the database and make changes... that is completely unsupported and you have no idea if there are other records in other tables that are associated with this.

# Execute not invoked by scheduler? 1/16/2008 3:53 PM Peter
Gravatar Hi,

to all of you having problem with scheduler not invoking Execute(Guid) method on SPJobDefinition:

Try executing this from cmd:

NET STOP SPTimerV3
NET START SPTimerV3

This restarts the scheduler. Hope it helps - it did for me.

Regards, Peter

# re: Creating Custom SharePoint Timer Jobs 1/24/2008 7:49 AM Mich
Gravatar Hi, I have created the wsp file added the solution to solution store and deployed it but i do not see it in the site collection features to activate?
iOne of my timer jobs does appear in the job definitions but never actually runs?
Has anyone any ideas i have followed instructions to the letter!

Thanks
Mich

# re: Creating Custom SharePoint Timer Jobs 1/24/2008 11:44 AM AC [MVP MOSS]
Gravatar Mitch-
Feature visible? The one I wrote up in the same was hidden, thus you have to activate from the command line. See the article for more info on why I recommend this approach.

# re: Creating Custom SharePoint Timer Jobs 1/25/2008 4:24 AM nadeem
Gravatar Andrew,

Thanks for a great post, I was able to successfully deploy the solution to my site.

But I have a bit of a problem,

"Task Logger" job is showing up in Timer Job status in Central admin, but I can't see it in Timer Job definition and therefore I couldn't stop the job, It is continuously running every 5 mins and creating listitems. The solution management page is empty and I don't see any solutions, can't see anything specific in features folder. Could you please tell me how to stop this job and what mistake have I done?

I tried many commands using stsadm but couldn't figure out the right one to fix the issue I have.

# re: Creating Custom SharePoint Timer Jobs 1/25/2008 8:22 AM AC [MVP MOSS]
Gravatar Nadeem-
Simply deactivate the Feature. It is a hidden Feature so you need to do this from the command line using STSADM

# re: Creating Custom SharePoint Timer Jobs 1/25/2008 3:03 PM nadeem
Gravatar Hi Andrew,

I m sorry to trouble you again but I couldn't resolve the issue.

Could you tell me if there is a way to search for hidden features through command line using STSADM. Since I can't see the feature in the Features folder as I've tried it many times before the solution was deployed successfully it is tough to remember when it was activated and also the feature name or the ID in order to deactivate/uninstall the feature. I tried -force, it says operation completed successfully but still doesn't remove the job from timer job status list the job doesn't show up in timer job definition though.

Thanks for all your help...

# re: Creating Custom SharePoint Timer Jobs 1/26/2008 8:37 PM AC [MVP MOSS]
Gravatar Nadeen-
The easy way: try installing it without the "-force" argument. If it says it is installed, then it was installed. :) After you do the whole uninstall, recyle IIS and the timer service to see if that fixes it.

I, along with many readers, have installed/run/uninstalled this many times without issues, so I can assure you it works just fine.

# re: Creating Custom SharePoint Timer Jobs 1/28/2008 2:16 AM Manoj
Gravatar Hello,

how do we add email notifications in the timer job.
I want to use SPEmailMessage which is part of MOSS. Instead of normal Mail for sending email notifications?

How can we get the SMTP address which we set in the outgoing email configuration in MOSS?

any help on this would be great.

Manoj

# re: Creating Custom SharePoint Timer Jobs 1/28/2008 7:29 AM AC [MVP MOSS]
Gravatar Manoj-
Look at the SPWebApplication object for the object that owns your timer job (site/site collection/web application). It has all the properties you set on for the email such as SPWebApplication.OutgoingMailSenderAddress, etc.

# re: Creating Custom SharePoint Timer Jobs 1/28/2008 8:54 AM Manoj
Gravatar Thanks AC.

But where do we set the email address of the receiver when sending a mail.
Also can we add an attach using SPWebApplication.
I was able too attach email using System.Net.Mail;


# re: Creating Custom SharePoint Timer Jobs 1/28/2008 12:45 PM AC [MVP MOSS]
Gravatar Manoj-
I don't understand... you mean who is going to receive the email? This doesn't have anything to do with SharePoint... just a property on the mail object in S.N.Mail I'd assume.

# re: Creating Custom SharePoint Timer Jobs 2/8/2008 6:33 AM Majid
Gravatar I have created a job using the following code :

ItemMonitorJob taskLoggerJob = new ItemMonitorJob("IWTJob", site.WebApplication);

SPMinuteSchedule schedule = new SPMinuteSchedule();
schedule.BeginSecond = 0;
schedule.EndSecond = 59;
schedule.Interval = 1;
taskLoggerJob.Schedule = schedule;
taskLoggerJob.Update();


The code executes fine no error but it doesnot appear under central administration. When I debug SPJobDefinitions list it appears there but not in the administration site even not executing upon defined schedule :(.

Please let me know whats wrong ?




# re: Creating Custom SharePoint Timer Jobs 2/9/2008 7:18 AM Manoj
Gravatar Hello,

how do we create monthly and yearly scheduler?

MonthlySchedule = new SPMonthlySchedule();
MonthlySchedule.BeginDay = 1;
MonthlySchedule.EndDay = 1;
MonthlySchedule.BeginMinute = 01;
MonthlySchedule.EndMinute = 59;

when i tried the above code. The scheduler does not get started?

thanks in advance


# re: Creating Custom SharePoint Timer Jobs 2/9/2008 10:36 AM AC [MVP MOSS]
Gravatar Majid-
Doesn't make sense. You should open a support ticket for this.

Manoj-
I haven't worked with the yearly schedue... sorry. You might need to open a support ticket for this

# re: Creating Custom SharePoint Timer Jobs 2/11/2008 11:35 PM Manoj
Gravatar Hello,

as any one created a daily and monthly schedule?

# re: Creating Custom SharePoint Timer Jobs 2/12/2008 9:44 AM Majid
Gravatar Thanks Andrew,

All worked in the end. Thanks alot for this wonderful post.

Majid

# re: Creating Custom SharePoint Timer Jobs 2/13/2008 10:29 AM bazztrap
Gravatar In a web Farm where central admin is on a different server ... where do you think the DLL's for timer service will reside and on which server will it be installed..



# re: Creating Custom SharePoint Timer Jobs 2/15/2008 5:57 AM Venkata apparao
Gravatar Hi,

It's good one to create a basic schedule. I succeeded in building one similar custom job. However, no luck while creating Hourly/Daily schedules. Job is appearing in Operations->Timer job definitions. But not executing ever.

Any Support Sir?

# Visual Studio template 2/27/2008 2:02 PM Alexander Brütt
Gravatar Hi,
I developed a visual studio template based on this stuff.

http://saftsack.fs.uni-bayreuth.de/~dun3/archives/visual-studio-2005-project-template-for-sharepoint-2007-timer-jobs/142.html

Greetings,
Alexander

# re: Creating Custom SharePoint Timer Jobs 3/5/2008 7:41 PM Gavin Barron
Gravatar I should have read the comments.....

I ran into the old code problem with my timer job too and have just posted a sample deployment script on my blog that will cover a full deploy and activation of a timer job feature.

http://gavinb.net/archive/2008/03/06/deploying-timer-jobs.aspx

-Gavin

# re: Creating Custom SharePoint Timer Jobs 3/7/2008 2:07 AM SP
Gravatar Hi Andrew,

I trying to use Excel Web Service in my timer job, but it does not work. It gives the following error:

"Excel Web Services could not determine the Windows SharePoint Services site context of the calling process."


I tried both the options, using the ExcelService.asmx web reference and Local Linking, (i.e. linking to Microsoft.Office.Excel.Server.WebServices.dll). In both the cases I get the same error, when I try to create an instance of ExcelService object.

What could be the problem?

SP

# re: Creating Custom SharePoint Timer Jobs 3/7/2008 9:32 AM AC [MVP MOSS]
Gravatar SP-
I suspect you are trying to get an instance using SPContext. Timer jobs don't run in the context of SharePoint as they are executed using the OWSTIMER.EXE process, not SharePoint.

# re: Creating Custom SharePoint Timer Jobs 3/14/2008 10:24 AM TANZHAN
Gravatar 看不懂!

# re: Creating Custom SharePoint Timer Jobs 3/24/2008 10:00 AM Ravi
Gravatar Hi,

I have tried creating the timer job using the code provided by you. I created a class libary project and added the two TaskLoggerJob and TaskLoggerJobInstaller classes i added the feature.xml from the downloaded solution and modified it accordingly to reference the assembly i created. Once i installed and activated the feature I see that the Job in the Timer Job Definition. When i try to activate it the Job and check its status in the Timer Job Status page. I see that teh Job fails. I am not understanding the reason why its failing.

I am the admin on the site for which i have activated the timer job. whats could be issue with the job? Is there any other reason which i havent performed.

# re: Creating Custom SharePoint Timer Jobs 3/26/2008 11:45 AM nagesh
Gravatar
Dear Andrew,

Iam new to SharePoint server.So what is the thing is I download TaskLogger_CustomTimerJob.zip.and added in the solution.when i buid the project i got the following Error.
please resolue my issue.


Error 1 The command ""C:\Program Files\Microsoft Cabinet SDK\BIN\MAKECAB.EXE" /F BuildSharePointPackage.ddf /D CabinetNameTemplate=AndrewConnell.TaskLoggerJob.wsp /D DiskDirectory1=bin\Debug\SpPackage\" exited with code 3. AndrewConnell.TaskLoggerJob


# re: Creating Custom SharePoint Timer Jobs 3/26/2008 4:26 PM AC [MVP MOSS]
Gravatar Nagesh-
Look at the Output window... doubt you have MAKECAB.EXE on your development machine.

# re: Creating Custom SharePoint Timer Jobs 4/3/2008 8:59 AM vignesh
Gravatar I am totally new to features in SharePoint 2007. While trying ur sample I am ABLE to install .wsp file using stsadm and also to deploy the solution globally. But then the feature is NOT present in the feature list of either Site Features or Site Collection Features. Where do I activate the feature from?

Do I have to do anything extra? Anything to do with the 'feature.xml'?

The assembly gets installed in GAC when i deploy the solution. Do I have to look for the feature in some particular site collection or site? Not sure abt this coz its deployed globally.

# re: Creating Custom SharePoint Timer Jobs 4/3/2008 9:06 AM AC [MVP MOSS]
Gravatar Vignesh-
Look at the feature.xml file for the scoping and visibility. As I said in the blog post, don't use visible Features when deploying timer jobs. You have to activate it from the command line, not from the Web UI.

# re: Creating Custom SharePoint Timer Jobs 4/9/2008 5:09 PM Daniel
Gravatar Hi,

I have the same issue as Laurent. I would be add an SPUser object to properties and an error occured like:
"The platform does not know how to deserialize an object of type Microsoft.SharePoint.SPUser. The platform can deserialize primitive types such as strings, integers, and GUIDs; other SPPersistedObjects or SPAutoserializingObjects; or collections of any of the above. Consider redesigning your objects to store values in one of these supported formats, or contact your software vendor for support. "

I try this:
try
{
foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
{
if (job.Name == SEND_EMAIL_JOB_NAME)
job.Delete();
}
}
catch { //error at "in site.WebApplication.JobDefinitions" with the same message}


and this:

site.WebApplication.JobDefinitions[SEND_EMAIL_JOB_NAME].Delete(); (// isnull)


How can I remove this Jobdefinition without editing database? Thx 4 hints

# re: Creating Custom SharePoint Timer Jobs 4/10/2008 10:06 AM AC [MVP MOSS]
Gravatar Daniel-
I'd just write something that iterates through all the jobs and use the VS debugger to inspect which one. Obviously something went wrong along the way for yours.

# re: Creating Custom SharePoint Timer Jobs 4/15/2008 4:37 PM Mo
Gravatar Hi Andrew,
Thanks for the post. I am trying to deploy the timer thru
VSeWSS 1.1

It creates a "Untitled 1" as feature name in WSP view.
I have feature.xml and element.xml added to the project.

Could you please give an idea of what the deployment file should contain (element.xml / feature.xml)
if the deployment is to be done thru VSeWSS 1.1

Thanks a lot,
Mo

# re: Creating Custom SharePoint Timer Jobs 4/15/2008 8:26 PM AC [MVP MOSS]
Gravatar Mo-
It is not possible to deploy or install timer jobs using the OOTB Feature schema so thus, VSeWSS does not have any native support for timer jobs. But you can create a Feature receiver that does the install just like I show in this post.

# re: Creating Custom SharePoint Timer Jobs 4/16/2008 6:20 AM Ruchi
Gravatar hi,

I simply want to know disadvantages of timer Job, and number of such jobs it will support. What I mean by this is like in SPS 2003, 2000 doc was max limit to work well with list. Is there any such restrcition on Timer Job, cause my client is asking me to create TimerJob for every single request. [which can be done immediately or scheduled].

Thanks
Ruchi

# re: Creating Custom SharePoint Timer Jobs 4/16/2008 9:54 AM AC [MVP MOSS]
Gravatar Ruchi-
Sorry, I don't understand your question. Timer jobs are really no different than scheduled tasks in Windows. They just run within the context of SharePoint.

# re: Creating Custom SharePoint Timer Jobs 4/23/2008 10:41 PM Ravi Shankar
Gravatar I created the Job like this
TaskLoggerJob taskLoggerJob = new TaskLoggerJob("Sync", SPContext.Current.Site.WebApplication);

SPMinuteSchedule schedule = new SPMinuteSchedule();
schedule.BeginSecond = 0;
schedule.EndSecond = 59;
taskLoggerJob.Schedule = schedule;
taskLoggerJob.Properties.Add("Key1", list_guid);
taskLoggerJob.Update();

Now in the Execute method how will i access this property that i stored in task logger in the Execute() method;

I tried this option but i am unable to retrieve the Key as it gives null reference

TaskLoggerJob taskLoggerJob = new TaskLoggerJob("Sync", SPContext.Current.Site.WebApplication);
if (taskLoggerJob.Properties.ContainsKey("Key1"))
{
string vals = Convert.ToString(taskLoggerJob.Properties["ListSync"]);
}

Please help me

# re: Creating Custom SharePoint Timer Jobs 4/24/2008 10:14 AM AC [MVP MOSS]
Gravatar Ravi-
You're checking for the existance of one key but looking for the value of something else "ListSync".

# re: Creating Custom SharePoint Timer Jobs 5/1/2008 6:50 AM Ravi Shankar
Gravatar Hi,

I have to execute a sync job an a particular list. i need to pass the Sourcelist and the targetlists to the timer job to execute the process. i am using the property bag of the job to store the values."KeyVal" is unique for each job that i create.

I am creating the timer job like this:

SPMinuteSchedule schedule = new SPMinuteSchedule();
schedule.BeginSecond = 0;
schedule.EndSecond = 59;
taskLoggerJob.Schedule = schedule;
taskLoggerJob.Properties.Add(KeyVal, strValue);
taskLoggerJob.Update();

Now in the execute method i want to retrieve the value that is stored in the property bag for this job. i am using the following code:

if (this.Properties.ContainsKey(KeyVal))
{
string Store = this.Properties[KeyVal].ToString();
}

But the system throws an error "KeyVal" doesnt exist in the current context. Please suggest how can i solve this issue



# re: Creating Custom SharePoint Timer Jobs 5/1/2008 7:25 AM AC [MVP MOSS]
Gravatar Ravi-
Not sure why that doesn't work. Have you checked out my article on MSDN that includes working with the hierarcial storage?
http://msdn2.microsoft.com/en-us/library/cc406686.aspx

# re: Creating Custom SharePoint Timer Jobs 5/7/2008 2:37 AM Martin
Gravatar Hello
I'm facing a problem :
EXECUTE permission denied on object 'proc_putObject', database 'SharePoint_Config', schema 'dbo'.
Owe asked obout needed permissions but there was no answer. Eric adviced to activate feature from stsadn tool, but I want to activate it from UI. What and where do I need to set up permissions for my user? If I am looged as an Administrator - everything works fine.
Best regards
Marcin

# re: Creating Custom SharePoint Timer Jobs 5/7/2008 7:47 AM AC [MVP MOSS]
Gravatar Martin-
It sounds as if you are using a Feature to install/uninstall your timer job and you are activating it via the Web interface. When you do this, you are inheriting the permissions of the the app pool that's running the site which won't have permissions on that proc. However if activate it using STSADM from the command line while logged in with an account that is part of the SharePoint farm's admin group, it will work. Look at the update at the bottom of this post from 7/2/2007... explains this in more depth (http://www.andrewconnell.com/blog/archive/2007/07/02/6067.aspx).

# re: Creating Custom SharePoint Timer Jobs 5/8/2008 5:19 AM Martin
Gravatar Hello
I have solved my problem out :)
In IIS i changed my application pool to Share Point Admin for my WebSite and the Timer Job has appeared in my Central Administartion. Now I'm going to "ask" my Timer Job to do something -> if any problem occur, Iwill write obout it.
Thank You for Your reply AC [MVP MOSS]
Best regards
Martin/Marcin

# re: Creating Custom SharePoint Timer Jobs 5/8/2008 9:04 AM AC [MVP MOSS]
Gravatar Martin-
That is EXACTLY what I was saying you don't want to do. Your application pool should not be running as the SharePoint service account... that's a huge security hole you just opened. Please read the posts I referenced. I would not recommend the approach you took to resove the issue.

# re: Creating Custom SharePoint Timer Jobs 5/8/2008 12:52 PM Deepak Aggarwal
Gravatar We have created one timer job and deployed it on out production farm with 2 FE and 1 Index Server and 2 Clustered DB server setup. The job was deployed successfully. One thing we noticed that the job is running only on one front end server not on the other FE server. we checked the Job defination but there it is only attached with only one FE server. If we stop the services of that FE server then JOB stop working. All other MS jobs are working on all FE servers successfully. Could you please help us to deploy the job on all FE servers?

Regards
Deepak

# re: Creating Custom SharePoint Timer Jobs 5/8/2008 2:14 PM AC [MVP MOSS]
Gravatar Deepak-
That's a locking thing... check out my MSDN article (http://msdn.microsoft.com/en-us/library/cc406686.aspx). The second section on "Creating Custom Timer Jobs" addresses this.

# Creating Custom SharePoint Timer Jobs 5/14/2008 10:22 AM Ravi Shankar
Gravatar Hi,

I was able to succesfuly create timer Jobs.. but am facing some issue with the timer jobs getting kicked off.. Even though iam creating minute jobs they just wait in the queue endlessly waiting to be executed.. I tried to use the stsadm -o execsvcadmjobs to start it forcefully yet no luck sometime they start sometime they wait endlessly.. Also if i am making any changes to the solution (i mean the Execute() code) need to restart the system to see through the changes that i have done.. Please help me solve these issues..

Regards,
Ravi Shankar

# re: Creating Custom SharePoint Timer Jobs 5/14/2008 2:23 PM Curt
Gravatar Andrew,
I've been searching for several days now....any help with scheduling a job to run DAILY (or even twice daily) would be greatly appreciated.

latest attempt:
SPDailySchedule myDailySchedule = new SPDailySchedule();
myDailySchedule.BeginHour = 12;
myDailySchedule.BeginMinute = 0;
myDailySchedule.BeginSecond = 0;
myDailySchedule.EndHour = ???; //***necessary ???
myDailySchedule.EndMinute = ???; //***necessary ???
myDailySchedule.EndSecond = ???; //***necessary ???
taskLoggerJob.Schedule = myDailySchedule;
taskLoggerJob.Update();

# re: Creating Custom SharePoint Timer Jobs 5/14/2008 9:50 PM AC [MVP MOSS]
Gravatar Ravi-
They are never running? Do you have the DST patch installed? When you update the timer job, one thing you def. want to do is restart the timer service for good measure.

Curt-
Those ranges say when the job can start. SharePoint determines the best time to kick it off based on the current load. So if you stay start anytime between 12:00:00 and 15:00:00, it has a 3hr range it can start within. I believe that's the case.

# re: Creating Custom SharePoint Timer Jobs 6/18/2008 11:30 PM nap
Gravatar andy,

I successfully run the stsadm command that you specified to use you prebuilt wsp, however, i could not locate the "
Task Logger" on my Site Collection Feature. am I missing on something here, or i need some configuration?

I hope you can help me.

Thanks!

# re: Creating Custom SharePoint Timer Jobs 6/19/2008 12:28 AM AC [MVP MOSS]
Gravatar nap-
You have to deploy the solution & activate the hidden Feature to get it installed.

# re: Creating Custom SharePoint Timer Jobs 6/19/2008 4:33 AM nap
Gravatar Andy,

alright, i can see now the Task Logger on the Timer Job Definition, however, i guess the execute() is not working... the list is now getting populated or updated with any new list. is there a way where i could test if the timer is running or working? is it available on the task manger?

here is the site where i created a Tasks List...
http://myurl/Lists/Tasks/AllItems.aspx

base on my understanding, if the timer is really working, ther must be some items visible on this page. isn't it?



# re: Creating Custom SharePoint Timer Jobs 6/24/2008 9:34 AM Dheepa B
Gravatar Does any one know how to programatically show the Last run Status of a job. I am able to show the LastRun time by calling SPJobdefinition.LastRunTime, But how will I get the status as to succeeded or failed status of the job when it was last run ?

# re: Creating Custom SharePoint Timer Jobs 6/28/2008 9:42 AM James
Gravatar Does Microsoft honestly think that users would not want to backup their farm on a daily or even weekly basis by using a custom timer job? Having to go through this to do something that should be built in is ridiculous.

# re: Creating Custom SharePoint Timer Jobs 6/28/2008 9:43 AM AC [MVP MOSS]
Gravatar James-
I don't get your point... all your settings are backed up. There is just no browser-based UI to install a custom timer job.

# re: Creating Custom SharePoint Timer Jobs 7/7/2008 4:07 PM Ani
Gravatar Hello Andrew

Need more clarification. Yet I have not installed, Here is the scenerio

Using your timeerjob solution we cam execute it depending on daily frequency if severity field is null. Every time it will add a new item to a Task list whenever it's executed and in that task list we can create workflow for “New Item” action and send mail to specified group.

My Only concern here will it add new task every time on update existing task also.

Please if possible explain me its functionality.

Ani





# re: Creating Custom SharePoint Timer Jobs 7/14/2008 1:42 AM jdxyw
Gravatar Hi I write my Timer Job step by step as yours.
When I activate my feature.the CPU usage becomes 100%.Could you tell me what make this happen

# re: Creating Custom SharePoint Timer Jobs 7/14/2008 9:10 AM AC [MVP MOSS]
Gravatar jdxyw-
Nope... that sounds like a heck of a timer job you created. This is not common.

# re: Creating Custom SharePoint Timer Jobs 7/15/2008 6:12 AM Daniel
Gravatar Hi Andrew,

first of all, thanks for this good articles about Custom Timer.

I have create a dll with the timer class. This class contains two constructors and the execute method of the SPJobDefinition class. I have install this dll in GAC and have restart IIS.

A little console application install the timer job in SharePoint.
I can see the job in admin centrale. In the state list of the jobs stands that the job is successful running.

But... he don't jump in the execute method. For testing he should create a textfile on C:\. The update method do that, the execute method don't do.

Have you any idea why the execute method don't work?

Thanks a lot.
Daniel

# re: Creating Custom SharePoint Timer Jobs 7/15/2008 6:21 AM AC [MVP MOSS]
Gravatar Daniel-
Have you verified it is not being called? Try attaching the debugger to the timer service and using an Assertion as I show in this article (http://msdn.microsoft.com/en-us/library/cc406686.aspx). Checked the logs?

# re: Creating Custom SharePoint Timer Jobs 7/15/2008 10:38 AM Paul
Gravatar Hi,

Wow, a very fast answer.
In the moment i get errors in the eventlogger. But, this error message refer to something, i have done yesterday in the execute method.
In my opinion he don't update the contents of my dll file.
But, i reinstall the dll in GAC, reset the IIS, and reinstall the job in SharePoint and delete the xml cache files. But he don't update the content of the execute method....

First of all.... i must check why he don't use the content of the new dll file.

After that i test your debug method from the mdsn article.

Thanks a lot.
Daniel


# re: Creating Custom SharePoint Timer Jobs 7/21/2008 12:07 PM ms
Gravatar Hi,

I have a project where i have a document library to submit helpdesk requests; once the item is submitted a custom workflow creates a helpdesk ticket. I have a column TicketStatus I want this updated when the ticket is closed. Will the timer job help to updated this column basically check the database for change and update the column. Or is there a better solution to achieve this.

Thanks
ms

# re: Creating Custom SharePoint Timer Jobs 7/21/2008 8:28 PM AC [MVP MOSS]
Gravatar MS-
No, timer jobs aren't a good fit here... that should be another step in your workflow.

# re: Creating Custom SharePoint Timer Jobs 7/27/2008 1:15 AM Ray
Gravatar Hi Andrew,

I am having the same problem as Ravi, the timer job simply isn't executing (as well as hundreds other jobs), i double checked the timer service it is running under administrative account. i used the same command stsadm -o execsvcadmjobs also no luck.
You commented that there is DST patch, what is this, is it included in SP1 (i have SP1 installed)? if yes what else should i check?

Thanks and Regards,
Ray

# re: Creating Custom SharePoint Timer Jobs 8/8/2008 3:12 PM paisleygo
Gravatar re: - 7bergen's experince Access to the path 'C:\Documents and Settings\All Users\Application Data\Microsoft\SharePoint\Config\bd189eb6-92d0-4ca5-87b0-770f542e3f0a\cache.ini' is denied.

I had this issue too

did it happen when moving from dev to test? We have one svc account running everything in dev - but test separates all teh services into separate accounts - an account for the portal apppool - I had to give that account access in sql to some stored procs before I got to the point where I get the 403

If anybody else has this issue - can you explain how to use service accounts when deploying features so that the feature receiver code has all the rights it neds? - Mybe I should make my app pool id match the db account?

(although I don't think our sys admin will go for that..)



# re: Creating Custom SharePoint Timer Jobs 8/15/2008 3:00 PM Matt
Gravatar Great article - very straight forward!

I do have a question, though.

My timer job involves hitting an external database and bringing in data to a SharePoint list.

When I activate the feature, it is getting activated on multiple servers, since its a multi-server farm, and so the timer job is running on each of those servers. I only want 1 server handling the timer job.

Any thoughts?

# re: Creating Custom SharePoint Timer Jobs 8/15/2008 3:18 PM AC [MVP MOSS]
Gravatar Matt-
Yup... you need to configure the proper lock type. Check my MSDN article (http://msdn.microsoft.com/en-us/library/cc406686.aspx) which discusses this. I think you want to lock it for the ContentDB... you'll also need to have some sort of a flag you check to see when it ran.

# re: Creating Custom SharePoint Timer Jobs 8/19/2008 10:28 AM Matt
Gravatar Thanks for the reply.

SPJobLockType.Job actually did the trick, since that ensures only 1 server runs the job.

# re: Creating Custom SharePoint Timer Jobs 8/20/2008 6:31 AM Hema
Gravatar Great article Andrew it was of great help-Thanks

If i give deploymentTarget ="WebFrontEnd" and deploy this solution to the Web Frontend Servers (Load-balanced) in a MOSS Server Farm environment, will the timer job run on all the frontend Servers at the specified time or only in one front end server?
It would be grateful if you can explain the behavior of the MOSS Load Balanced environment since i`m new to working in Farm environment.

Thanks in advance
Hema


# re: Creating Custom SharePoint Timer Jobs 8/20/2008 8:26 AM Rafik
Gravatar Hi Andrew,

first of all, thank u very much for this good article.
I created the job timer class and then i created the feature receiver class.
I deployed the job timer dll in GAC
and i installed the event receiver feature and activated it with astadm.
The Job is added correctly but i dont see it in the admin panel and also the task list is not populated.
Can u help what the problem is.
Thank u very much.

# re: Creating Custom SharePoint Timer Jobs 8/20/2008 9:56 AM AC [MVP MOSS]
Gravatar Hema-
Scroll up a bit and look at Matt's question with my response and his follow up. You use a locking mechanism to keep it from running on multiple machines

Rafik-
Not sure what you mean by not seeing it in the admin panel. Compare your code to the downloads I provide as they work.

# re: Creating Custom SharePoint Timer Jobs 8/20/2008 12:11 PM Rafik
Gravatar thank u for your response.
the problem is that when i go to admin central and i browse job timers, i dont see that i created.
I checked by code if my timer job is created and i got that:
Status: Online
Name: my Timer Job
last date execution: 01/01/0001 00:00:00

so that mean my timer job is added but is never executed. I leave the execute function empty to be sure that the problem is not related to my code.
Until now, i dont fix the problem



# re: Creating Custom SharePoint Timer Jobs 8/20/2008 2:36 PM AC [MVP MOSS]
Gravatar Rafik-
Check the SP & Event logs... you could also try recycling IIS... it's apparent the install didn't go well.

# re: Creating Custom SharePoint Timer Jobs 8/22/2008 5:27 AM Jonas
Gravatar Great article!

One question: Shouldn't you Dispose() the SPSite-object used in the Execute()-method? Maybe you skipped it for simplicity, or are there any other reason?

# re: Creating Custom SharePoint Timer Jobs 8/22/2008 11:38 AM AC [MVP MOSS]
Gravatar Jonas-
Yeah... good catch :)

# Sharepoint Problem for Timer JOBS Event Log Error URI INVALID: URI is empty 8/23/2008 5:13 PM Nag...
Gravatar hi,

I am facing some problem in Farm environment when we deploy some timer jobs in Production.

we used WSP Package to deploy 5 timer jobs at once to make deployment easier, when we deploy this on single server its working fine, jobs status success.

when deploy this in Farm environment getting EventLog errors

"URI Invalid : URI is empty" for each job getting the same error. Please could you help me what coud be the cause for getting this issue.

Thanks in advance.
nag..

# re: Creating Custom SharePoint Timer Jobs 8/24/2008 8:48 AM AC [MVP MOSS]
Gravatar Nag-
Sorry... I haven't seen that. Other than debugging, either post to the forum (http://forums.msdn.microsoft.com/en-US/sharepointdevelopment/threads/) or open a support ticket with microsoft.

# re: Creating Custom SharePoint Timer Jobs 8/25/2008 3:07 PM nag
Gravatar HI, thanks for your quick response.

I have one query, In farm environment we have 4 servers.

Is it required to deploy all jobs invidually on each server using batch scripts. this would get resolve my issue?

currently we are deploying using single url which is mapped to farm environment using NLB.

thanks,
nag..

# re: Creating Custom SharePoint Timer Jobs 8/25/2008 3:54 PM M&M
Gravatar Hi,
I added lines to debug (per another article you wrote), but I don't get the pop-up window. However, in the System event log it says
"Application popup: Assertion Failed: Abort=Quit, Retry=Debug, Ignore=Continue : " On the timer job status page my job shows a 'status' of 'Initialized and 'Progress of 0%. Any ideas??
Matt


# re: Creating Custom SharePoint Timer Jobs 8/27/2008 7:46 AM AC [MVP MOSS]
Gravatar Nag-
If you deploy using WSP's, which you should, it will be deployed to all servers. My sample download in this blog post demonstrates this.

M&M
You certainly should have seen the popup on the server... even the event log shows it. Not sure about this one... sorry.

# re: Creating Custom SharePoint Timer Jobs 8/28/2008 4:07 PM Sucheta Patil
Gravatar Thanks for the very useful article. I have written a custom timer job according to your article. The job ran but got an exception in the Execute method. I retracted and deleted the solution. So I fixed that error and then again added the dll to GAC (I could not use gacutil, I dragged and dropped to winodws\assembly folder) and then again added and deployed the solution and activated solution. But I am still getting the old error and when I debugged, I found that even though the break point is reached in the code it seems it is still executing the old dll. Am I missing something here? Do I need to change the version of the assembly?

Thanks.

# re: Creating Custom SharePoint Timer Jobs 8/29/2008 11:48 AM AC [MVP MOSS]
Gravatar Sucheta-
Sounds like the DLL is cached. Try recycling IIS or the timer job.

# re: Creating Custom SharePoint Timer Jobs 9/2/2008 9:43 AM Vidhi
Gravatar Hi Andrew /David / Rajesh ,
I could see similar posts but really could not find the aapropriate reply to the following :-

Need to use the web.config to fetch values using ConfigurationManager.The key in the config value would be a Site URL to fetch lists and other stuff.
Buisness logic that would be impemented in a another class project file would be called from the overriden Execute() method .
The class project file needs to access the config values but not sure where and which config file would it read from ???

Response would be highly appreciated.
Thanks

# re: Creating Custom SharePoint Timer Jobs 9/2/2008 11:47 AM AC [MVP MOSS]
Gravatar Vidhi-
Your code will need to take into account how to get access to the web.config of the Web application you desire.

# re: Creating Custom SharePoint Timer Jobs 9/2/2008 11:42 PM Vidhi
Gravatar AC -
Eaxctly thats what is something I am looking for. I am not sure which web.config does my code looks in for and where should it be placed correctly so that the code can read the AppSettings / GetSection form the configuration manager.
I tried placing the config file under :C:\Inetpub\wwwroot\wss\VirtualDirectories\2000
but did not work.

Thanks

# re: Creating Custom SharePoint Timer Jobs 9/3/2008 12:07 AM AC [MVP MOSS]
Gravatar Vidhi-
Wait... you just want to store config data for your timer job? The web.config is NOT where you should be putting it. I cover different options in my MSDN white paper: http://www.andrewconnell.com/blog/archive/2008/04/15/More-help-on-creating-custom-timer-jobs-and-a-useful.aspx

# re: Creating Custom SharePoint Timer Jobs 9/17/2008 4:00 PM AZI
Gravatar Hi Andrew,
Thank you fo rhte great article.
I am very new to MOSS and timer job.My timer job has successfully created (At least based on command prompt). Thanks to your article!
My assembly shows in GAC. Also my feature shows under site feature in central admin.
However I have 2 questions:
1. I cannot see my timer job under timer job defenition. Where did I go wrong?
2. How can I create a timer job that send an automatic email after 30 days of filling a field on infopath form?

Thank you in advance.


# re: Creating Custom SharePoint Timer Jobs 9/26/2008 12:07 PM nancy
Gravatar Great article Andrew. Thank you!

I have a timer job feature, which globally has been deployed.

I use the following commands in sequence to remove/uninstall a solution (.wsp) from a site:

stsadm -o uninstallfeature -name MyTimerJob -force
stsadm -o retractsolution -name MyTimerJob.wsp -immediate -allcontenturls
stsadm -o execadmsvcjobs
stsadm -o deletesolution -name MyTimerJob.wsp -override
stsadm -o execadmsvcjobs
iisreset

Step works fine. But when it tries to retrsact the solution it says:

"This solution contains no resources scoped for a web application and cannot be retracted from a particular web application."

The end result: MyTimerJob feature has been removed under site feature. However I can still view my "MyTimerJob" under job definition.
Any idea why??????

# re: Creating Custom SharePoint Timer Jobs 9/26/2008 4:54 PM AC [MVP MOSS]
Gravatar Nancy-
First, your timer job is not deployed to a web app, it's deployed to the farm (globally). Thus, there is no need for "-allcontenturls" in the retractsolution because there are no URLs to remove it from.

# re: Creating Custom SharePoint Timer Jobs 9/29/2008 4:36 PM nancy
Gravatar Thanks alot for the respond. It worked like magic!

I have another problem that I have been researching for a while now...no luck.

I can view my timer job under definition.
My timer job(that inherits SPJobDefinition) is set to run every minute just to make sure it's working.
However seems like the execute() won't fire anything.
I used:
NET STOP SPTimerV3 and NET START SPTimerV3 and iisreset. still no luck.
I see no event in my event viewer.
Any idea???!!!

# re: Creating Custom SharePoint Timer Jobs 9/30/2008 8:15 AM nancy
Gravatar Also I thought this might be relevant: My job status shown as 100% failed.
Thank you.

# re: Creating Custom SharePoint Timer Jobs 10/1/2008 3:40 PM Rajeev
Gravatar Great article Andrew, Thank you,
When I tried to do this, debugger is not hitting execute method. Please help me regarding this.

Thanks

# re: Creating Custom SharePoint Timer Jobs 10/1/2008 5:56 PM AC [MVP MOSS]
Gravatar Rajeev-
You need to deploy the debugging symbols to the GAC: http://andrewconnell.com/blog/archive/2008/06/11/SharePoint-Debugging-and-Logging-Tips-and-Tricks.aspx

Comments have been closed on this topic.

Copyright © 2003 - 2010 Andrew Connell
Creative Commons License 
This work is licensed under a Creative Commons License
Site design by Heather Solomon.

 
 
MOSS WCM Training
Looking for MOSS 2007 WCM developer training? Look no further! I teach my 5-day hands-on and online WCM classes for developers I offer through my company: Critical Path Training.

Get more information on the WCM courses!