当前位置:编程学习 > 网站相关 >>

sharepoint 2010 如何创建一个timer job

在sharepoint的开发和应用中,经常会使用到,需要定时执行或者更新数据,我们可以用sharepoint自带的timer job来实现。
 
1。创建一个sharepoint 项目,名称为TimerJobTest;
 
2。创建一个class文件,名称为TimerJobClass;继承SPJobDefinition,如下图
 
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Administration;
namespace TimerJobTest
{
    public class TimerJobClass : SPJobDefinition
    {
        public TimerJobClass(): base(){}
        public TimerJobClass(string jobName, SPService service, SPServer server, 
            SPJobLockType targetType)
            : base(jobName, service, server, targetType)
        {
 
        }
        public TimerJobClass(string jobName, SPWebApplication webApplication)
            : base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
        {
            this.Title = jobName;
        }
 
        public override void Execute(Guid contentDbId)
        {
           //这里就是我们要执行的函数方法
        }
    }
}
 
 
3。添加一个feature,名称为TimerJob,并且选择范围为site,如下图:
 
 
4。添加一个事件接收器,如下图:
 
 
 
5。需要override其中的两个函数,
 
override void FeatureActivated(SPFeatureReceiverProperties properties),部署timer job函数
 
override void FeatureDeactivating(SPFeatureReceiverProperties properties) 删除timer job函数
 
方法如下:
 
 const string JOB_NAME = "TimerJobTest";
        // Uncomment the method below to handle the event raised after a feature has been activated.
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;
 
            // make sure the job isn't already registered
            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
            {
                if (job.Name == JOB_NAME)
                {
                    job.Delete();
                }
            }
            // install the job
            TimerJobClass Doc = new TimerJobClass(JOB_NAME, site.WebApplication);
            SPMinuteSchedule schedule = new SPMinuteSchedule();
            schedule.BeginSecond = 0;
            schedule.EndSecond = 59;
            schedule.Interval = 1;
            Doc.Schedule = schedule;
            Doc.Update();
        }
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;
            // delete the job
            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
            {
 
                if (job.Name == JOB_NAME)
                {
                    job.Delete();
                }
            }
        }
 
6。部署之后,到管理中心,作业定义中,查看是否已经部署成功,如下图,我们看到,timerjobTest已经成功部署,如下图
 
 
7。需要重新启动服务,如下图
 
 
这时候我们的timer job 就创建完成了。
 
补充:综合编程 , 其他综合 ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,