Create Custom Sharepoint Timer Job and execute it.

on Tuesday, August 11, 2009


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;
using System.IO;

namespace SampleTimerJob
{
public class TaskCreatorJob :SPJobDefinition
{
public TaskCreatorJob()
: base()
{
}
public TaskCreatorJob(string jobName, SPService service, SPServer server, SPJobLockType targetType)
: base(jobName, service, server, targetType)
{

}

public TaskCreatorJob(string jobName, SPWebApplication webApplication)

: base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
{
this.Title = "Task Logger";
}

public override void Execute(Guid targetInstanceId)
{
Console.WriteLine("Job is executing"+ DateTime.Now.ToLongDateString());
SPWebApplication webApplication = this.Parent as SPWebApplication;
SPContentDatabase db = webApplication.ContentDatabases[targetInstanceId];
SPDocumentLibrary docLib =db.Sites[0].RootWeb.Lists["Invoices"] as SPDocumentLibrary;
byte[] bytes=File.ReadAllBytes("c:\\logs.txt");
SPListItem item = db.Sites[0].RootWeb.Files.Add(docLib.RootFolder.Url + "/" + DateTime.Now.ToString("ddMMyyyyhhmmss"), bytes, true).Item;
item["Title"] = DateTime.Now.ToString();
item.Update();
//taskItem.Update();

//SPWebApplication webApplication = this.Parent as SPWebApplication;
//SPContentDatabase db = webApplication.ContentDatabases[targetInstanceId];
//SPList taskList = db.Sites[0].RootWeb.Lists["Tasks"];
//SPListItem taskItem = taskList.Items.Add();
//taskItem["Title"] = DateTime.Now.ToString();
//taskItem.Update();
//taskItem.Update();
base.Execute(targetInstanceId);
}
}
}




Execute it Programmatically

SPSite site = new SPSite("http://ramittalw09:777/");
//SPJobDefinition jobDef = site.WebApplication.JobDefinitions["TaskLogger"];
foreach (SPJobDefinition jobDef in site.WebApplication.JobDefinitions)
{
if (jobDef != null && jobDef.Name == "TaskLogger")
{
jobDef.Execute(site.ContentDatabase.Id);
break;
}
}

0 comments: