定时任务 Timer job 【转载】
最近最要在MOSS的项目任务中写一个定时提醒的功能,经过考虑采用Timer job来实现,配置信息采用XML文件
<Items>
<Item>
<ListUrl>
</ListUrl>
<Field day="0" name="截止日期" startname="创建时间">
</Field>
<Body>
</Body>
<ToField>
</ToField>
</Item>
</Items>
以下是代码:
TimerExecute类是执行发送邮件功能类
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
using System.Xml;
namespace MossJob
{
public class TimerExecute
{
public void Execute(SPWeb web, string siteUrl)
{
//xml配置文件信息
SPListItem it = web.Lists["timerjob"].Items[0];
SPFile file = it.File;
XmlDocument doc = new XmlDocument();
doc.Load(file.OpenBinaryStream());
XmlNode root = doc.SelectSingleNode("Items");
XmlNodeList nodes = root.SelectNodes("Item");
foreach (XmlNode node in nodes)
{
string listUrl = siteUrl + node.SelectSingleNode("ListUrl").InnerText;
SPList list = new SPSite(listUrl).OpenWeb().GetList(listUrl);
SPView view = list.DefaultView;
view.Scope = SPViewScope.Recursive;
SPQuery query = new SPQuery(view);
XmlNode nodeField = node.SelectSingleNode("Field");
XmlNode nodeBody = node.SelectSingleNode("Body");
XmlNode nodeToField=node.SelectSingleNode("ToField");
string strDay = nodeField.Attributes["day"].Value;
string strField = nodeField.Attributes["name"].Value;
string strStartName = nodeField.Attributes["startname"].Value;
string strQuery = "<Where><Neq><FieldRef Name='Status' /><Value Type='Text' >已完成</Value></Neq></Where>";
query.Query = strQuery;
SPListItemCollection items = list.GetItems(query);
foreach (SPListItem item in items)
{
SPListItem itemRow = list.Items.GetItemById(item.ID);
int diff = (Convert.ToDateTime(itemRow[strField] + string.Empty) - DateTime.Now).Days;
if (strDay == "0")
{
if ((Convert.ToDateTime(itemRow[strField] + string.Empty) - Convert.ToDateTime(itemRow[strStartName] + string.Empty)).Days / 2 >= diff)
{
SendMail(itemRow, nodeBody.InnerText, nodeToField.InnerXml,root.Attributes["path"].Value);
}
}
else if (Convert.ToInt32(strDay) >= diff)
{
SendMail(itemRow, nodeBody.InnerText, nodeToField.InnerXml,root.Attributes["path"].Value);
}
}
}
}
public void SendMail(SPListItem item,string strBody,string toFiled,string path)
{
string strAssignChange = "(到期提醒)";
SPList list = item.ParentList;
StringBuilder strFieldValue = new StringBuilder();
foreach (string strField in list.DefaultView.ViewFields)
{
if (strField != "Attachments")
{
strFieldValue.Append(this.GetValue(strField, list, item));
}
}
string strEmailBody = strBody;
SPWeb web = list.ParentWeb;
string strWebUrl = web.Url;
string strWebTitle = web.Title;
string strItemTitle = item.Title;
string strItemUrl = web.Site.Url + item.ParentList.DefaultViewUrl.Substring(0, item.ParentList.DefaultViewUrl.LastIndexOf("/")) + "/dispform.aspx?ID=" + item.ID.ToString();
string strListUrl = strWebUrl + "/" + list.DefaultViewUrl.Substring(0, list.DefaultViewUrl.LastIndexOf("/"));
string strListTitle = list.Title;
string strUpdated = item["Modified"] + string.Empty;
SPUser user = web.AllUsers.GetByID(Convert.ToInt32(item["Author"].ToString().Split(';')[0]));
string strAuthor = user.Name;
string strSubject = strListTitle + "-" + strItemTitle + strAssignChange;
try
{
toFiled = toFiled.Trim(';');
string[] strUsers = toFiled.Split(';');
foreach (string field in strUsers)
{
if (item[field].GetType() == typeof(SPFieldUserValueCollection))
{
SPFieldUserValueCollection users = item[field] as SPFieldUserValueCollection;
foreach (SPFieldUserValue u in users)
{
Microsoft.SharePoint.Utilities.SPUtility.SendEmail(web, true, false, u.User.Email, strSubject, strEmailBody);
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path, true))
{
sw.WriteLine("ItemID=" + item.ID.ToString() + "User=" + u.User.LoginName + " DateTime=" + DateTime.Now.ToString());
}
}
}
else
{
try
{
string strFieldUser = item[field] + string.Empty;
if (strFieldUser != "")
{
SPUser fieldUser = web.AllUsers.GetByID(Convert.ToInt32(strFieldUser.Split(';')[0]));
Microsoft.SharePoint.Utilities.SPUtility.SendEmail(web, true, false, fieldUser.Email, strSubject, strEmailBody);
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path, true))
{
sw.WriteLine("ItemID=" + item.ID.ToString() + "User="+fieldUser.LoginName+" DateTime=" + DateTime.Now.ToString());
}
}
}
catch (Exception ex)
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path, true))
{
sw.WriteLine("source=" + ex.Source + " Message=" + ex.Message);
}
}
}
}
}
catch(Exception ex)
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path, true))
{
sw.WriteLine("source=" + ex.Source + " Message=" + ex.Message);
}
}
}
public string GetValue(string strInnerName, SPList list, SPListItem item)
{
SPField field = list.Fields.GetFieldByInternalName(strInnerName);
string strTitle = field.Title;
string strValue = string.Empty;
string strEdit = string.Empty;
strValue = field.GetFieldValueAsText(item[strTitle]);
strEdit = " ";
string str = "<tr><td class='formlabel'>{0}:</td><td class='formbody'>{1}</td><td class='altvb'>{2}</td></tr>";
str = string.Format(str, strTitle, strValue, strEdit);
return str;
}
}
}
TaskListTimerJob 类继承SPJobDefinition,实现定时提醒
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
using System.Xml;
namespace MossJob
{
public class TaskListTimerJob:SPJobDefinition
{
public TaskListTimerJob()
: base()
{
}
public TaskListTimerJob(string _timername, SPWebApplication _wp)
: base(_timername, _wp, null, SPJobLockType.ContentDatabase)
{
this.Title = _timername;
}
public override void Execute(Guid targetInstanceId)
{
//base.Execute(targetInstanceId);
try
{
SPWebApplication webapp = this.Parent as SPWebApplication;
SPContentDatabase contentdb = webapp.ContentDatabases[targetInstanceId];
string siteUrl = contentdb.Sites[0].Url;
SPWeb web = contentdb.Sites[0].RootWeb;
new TimerExecute().Execute(web, siteUrl);
}
catch (Exception ex)
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter("c:\timerjob.txt", true))
{
sw.WriteLine("source=" + ex.Source + " Message=" + ex.Message);
}
}
}
}
}
把上面工程的dll 放到GAC中
Program 是控制台程序,用来部署timer job ,也可以用feature来部署,用控制台程序部署和卸载比较方便
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MossJob;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
using System.Xml;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
try
{
SPSite site = new SPSite("http://localhost/");
SPWebApplication web = site.WebApplication;
foreach (SPJobDefinition job in web.JobDefinitions)
{
string name = job.Title;
if (name == "MyCustomJobSendTaskMail")
{
job.Delete();
}
}
TaskListTimerJob newJob = new TaskListTimerJob("MyCustomJobSendTaskMail", site.WebApplication);
SPSchedule schedule = SPSchedule.FromString("daily at 20:46:00");
newJob.Schedule = schedule;
newJob.Update();
Console.WriteLine("部署成功");
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
}
} }
至此timer job 开发和部署完成,Timer job 主要是继承SPJobDefinition类,重写Execute方法即可。
<Items>
<Item>
<ListUrl>
</ListUrl>
<Field day="0" name="截止日期" startname="创建时间">
</Field>
<Body>
</Body>
<ToField>
</ToField>
</Item>
</Items>
以下是代码:
TimerExecute类是执行发送邮件功能类
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
using System.Xml;
namespace MossJob
{
public class TimerExecute
{
public void Execute(SPWeb web, string siteUrl)
{
//xml配置文件信息
SPListItem it = web.Lists["timerjob"].Items[0];
SPFile file = it.File;
XmlDocument doc = new XmlDocument();
doc.Load(file.OpenBinaryStream());
XmlNode root = doc.SelectSingleNode("Items");
XmlNodeList nodes = root.SelectNodes("Item");
foreach (XmlNode node in nodes)
{
string listUrl = siteUrl + node.SelectSingleNode("ListUrl").InnerText;
SPList list = new SPSite(listUrl).OpenWeb().GetList(listUrl);
SPView view = list.DefaultView;
view.Scope = SPViewScope.Recursive;
SPQuery query = new SPQuery(view);
XmlNode nodeField = node.SelectSingleNode("Field");
XmlNode nodeBody = node.SelectSingleNode("Body");
XmlNode nodeToField=node.SelectSingleNode("ToField");
string strDay = nodeField.Attributes["day"].Value;
string strField = nodeField.Attributes["name"].Value;
string strStartName = nodeField.Attributes["startname"].Value;
string strQuery = "<Where><Neq><FieldRef Name='Status' /><Value Type='Text' >已完成</Value></Neq></Where>";
query.Query = strQuery;
SPListItemCollection items = list.GetItems(query);
foreach (SPListItem item in items)
{
SPListItem itemRow = list.Items.GetItemById(item.ID);
int diff = (Convert.ToDateTime(itemRow[strField] + string.Empty) - DateTime.Now).Days;
if (strDay == "0")
{
if ((Convert.ToDateTime(itemRow[strField] + string.Empty) - Convert.ToDateTime(itemRow[strStartName] + string.Empty)).Days / 2 >= diff)
{
SendMail(itemRow, nodeBody.InnerText, nodeToField.InnerXml,root.Attributes["path"].Value);
}
}
else if (Convert.ToInt32(strDay) >= diff)
{
SendMail(itemRow, nodeBody.InnerText, nodeToField.InnerXml,root.Attributes["path"].Value);
}
}
}
}
public void SendMail(SPListItem item,string strBody,string toFiled,string path)
{
string strAssignChange = "(到期提醒)";
SPList list = item.ParentList;
StringBuilder strFieldValue = new StringBuilder();
foreach (string strField in list.DefaultView.ViewFields)
{
if (strField != "Attachments")
{
strFieldValue.Append(this.GetValue(strField, list, item));
}
}
string strEmailBody = strBody;
SPWeb web = list.ParentWeb;
string strWebUrl = web.Url;
string strWebTitle = web.Title;
string strItemTitle = item.Title;
string strItemUrl = web.Site.Url + item.ParentList.DefaultViewUrl.Substring(0, item.ParentList.DefaultViewUrl.LastIndexOf("/")) + "/dispform.aspx?ID=" + item.ID.ToString();
string strListUrl = strWebUrl + "/" + list.DefaultViewUrl.Substring(0, list.DefaultViewUrl.LastIndexOf("/"));
string strListTitle = list.Title;
string strUpdated = item["Modified"] + string.Empty;
SPUser user = web.AllUsers.GetByID(Convert.ToInt32(item["Author"].ToString().Split(';')[0]));
string strAuthor = user.Name;
string strSubject = strListTitle + "-" + strItemTitle + strAssignChange;
try
{
toFiled = toFiled.Trim(';');
string[] strUsers = toFiled.Split(';');
foreach (string field in strUsers)
{
if (item[field].GetType() == typeof(SPFieldUserValueCollection))
{
SPFieldUserValueCollection users = item[field] as SPFieldUserValueCollection;
foreach (SPFieldUserValue u in users)
{
Microsoft.SharePoint.Utilities.SPUtility.SendEmail(web, true, false, u.User.Email, strSubject, strEmailBody);
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path, true))
{
sw.WriteLine("ItemID=" + item.ID.ToString() + "User=" + u.User.LoginName + " DateTime=" + DateTime.Now.ToString());
}
}
}
else
{
try
{
string strFieldUser = item[field] + string.Empty;
if (strFieldUser != "")
{
SPUser fieldUser = web.AllUsers.GetByID(Convert.ToInt32(strFieldUser.Split(';')[0]));
Microsoft.SharePoint.Utilities.SPUtility.SendEmail(web, true, false, fieldUser.Email, strSubject, strEmailBody);
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path, true))
{
sw.WriteLine("ItemID=" + item.ID.ToString() + "User="+fieldUser.LoginName+" DateTime=" + DateTime.Now.ToString());
}
}
}
catch (Exception ex)
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path, true))
{
sw.WriteLine("source=" + ex.Source + " Message=" + ex.Message);
}
}
}
}
}
catch(Exception ex)
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path, true))
{
sw.WriteLine("source=" + ex.Source + " Message=" + ex.Message);
}
}
}
public string GetValue(string strInnerName, SPList list, SPListItem item)
{
SPField field = list.Fields.GetFieldByInternalName(strInnerName);
string strTitle = field.Title;
string strValue = string.Empty;
string strEdit = string.Empty;
strValue = field.GetFieldValueAsText(item[strTitle]);
strEdit = " ";
string str = "<tr><td class='formlabel'>{0}:</td><td class='formbody'>{1}</td><td class='altvb'>{2}</td></tr>";
str = string.Format(str, strTitle, strValue, strEdit);
return str;
}
}
}
TaskListTimerJob 类继承SPJobDefinition,实现定时提醒
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
using System.Xml;
namespace MossJob
{
public class TaskListTimerJob:SPJobDefinition
{
public TaskListTimerJob()
: base()
{
}
public TaskListTimerJob(string _timername, SPWebApplication _wp)
: base(_timername, _wp, null, SPJobLockType.ContentDatabase)
{
this.Title = _timername;
}
public override void Execute(Guid targetInstanceId)
{
//base.Execute(targetInstanceId);
try
{
SPWebApplication webapp = this.Parent as SPWebApplication;
SPContentDatabase contentdb = webapp.ContentDatabases[targetInstanceId];
string siteUrl = contentdb.Sites[0].Url;
SPWeb web = contentdb.Sites[0].RootWeb;
new TimerExecute().Execute(web, siteUrl);
}
catch (Exception ex)
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter("c:\timerjob.txt", true))
{
sw.WriteLine("source=" + ex.Source + " Message=" + ex.Message);
}
}
}
}
}
把上面工程的dll 放到GAC中
Program 是控制台程序,用来部署timer job ,也可以用feature来部署,用控制台程序部署和卸载比较方便
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MossJob;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
using System.Xml;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
try
{
SPSite site = new SPSite("http://localhost/");
SPWebApplication web = site.WebApplication;
foreach (SPJobDefinition job in web.JobDefinitions)
{
string name = job.Title;
if (name == "MyCustomJobSendTaskMail")
{
job.Delete();
}
}
TaskListTimerJob newJob = new TaskListTimerJob("MyCustomJobSendTaskMail", site.WebApplication);
SPSchedule schedule = SPSchedule.FromString("daily at 20:46:00");
newJob.Schedule = schedule;
newJob.Update();
Console.WriteLine("部署成功");
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
}
} }
至此timer job 开发和部署完成,Timer job 主要是继承SPJobDefinition类,重写Execute方法即可。