1.创建一个空的SharePoint项目从Visual Studio 2010或2012的名称TSTimerJob。你可以给任何名义到这个项目,但在我们的例子中,我们使用这个名字。按“确定”,并选择“部署为场解决方案”
2.输入一个本地站点调试的URL。信任级别选择“部署为场解决方案”。
3.TSTimerJob - >添加 - >“新建项目” - >类 ->CustomTimerJob.cs
4.CustomTimerJob.cs 代码:
class CustomTimerJob : SPJobDefinition
{
public CustomTimerJob() : base() { }
public CustomTimerJob(string jobName, SPService service) :
base(jobName, service, null, SPJobLockType.None)
{
this.Title = "TSTimerJob";
}
public CustomTimerJob(string jobName, SPWebApplication webapp) :
base(jobName, webapp, null, SPJobLockType.ContentDatabase)
{
this.Title = "TSTimerJob";
}
public override void Execute(Guid targetInstanceId)
{
using (SPSite site = new SPSite("http://mossinx:80"))
{
using (SPWeb web = site.OpenWeb())
{
SPList spList = web.Lists["AlertMailTest"];
SPListItem newItem = spList.Items.Add();
newItem["Title"] = "New"+DateTime.Now.ToString("yyyy/MM/dd");
newItem.Update();
}
}
}
}
5.添加一个新的feature,注册自定义计时器作业。右键单击在解决方案资源管理器里面的项目特点,并单击“添加功能”。
6.重命名功能CustomTimerJobFeature
7.Scope选择WebApplication
8.添加功能事件接收器,右键点击 CustomTimerJobFeature,
并选择“添加事件接收器”。
编写以下代码到 CustomTimerJobFeatureEventReceiver.cs类,
public class TSTimerJobFeatureEventReceiver : SPFeatureReceiver
{
const string JobName = "TSTimerJob";
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPWebApplication parentWebApp = (SPWebApplication)properties.Feature.Parent;
SPSite site = properties.Feature.Parent as SPSite;
DeleteExistingJob(JobName, parentWebApp);
CreateJob(parentWebApp);
});
}
catch (Exception ex)
{
throw ex;
}
}
private bool CreateJob(SPWebApplication site)
{
bool jobCreated = false;
try
{
CustomTimerJob job = new CustomTimerJob(JobName, site);
SPMinuteSchedule schedule = new SPMinuteSchedule();
schedule.BeginSecond = 0;
schedule.EndSecond = 59;
schedule.Interval = 15;
job.Schedule = schedule;
job.Update();
}
catch (Exception)
{
return jobCreated;
}
return jobCreated;
}
public bool DeleteExistingJob(string jobName, SPWebApplication site)
{
bool jobDeleted = false;
try
{
foreach (SPJobDefinition job in site.JobDefinitions)
{
if (job.Name == jobName)
{
job.Delete();
jobDeleted = true;
}
}
}
catch (Exception)
{
return jobDeleted;
}
return jobDeleted;
}
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
SPWebApplication parentWebApp = (SPWebApplication)properties.Feature.Parent;
DeleteExistingJob(JobName, parentWebApp);
}
}
9.右击项目--->Deploy
10.打开Central Admin,点开左边的System Settings,选择Manage Farm Solutions。
11.之后你会看到我们的tstimerjob是not deployed,给他deploy一下
12.点击OK
13.至此,应该是可以了,但是有可能你的timerjob没有激活,激活步骤。
Central Administration-->Manage web applications-->你的端口-->Manage Features-->找到你的timerjob-->active