做这个定时器Andrew Connell的博客给我很大的帮助。里面有所有的源代码,思路也很清晰
http://www.andrewconnell.com/blog/articles/CreatingCustomSharePointTimerJobs.aspx
主要是继承SpJobDefinition,改写几个构造体和Execute的方法.基本代码的模式就是这个样子:
下面是自己的一段代码有些凌乱:
另外一个类就是:
用Stsadm.exe来部署
http://www.andrewconnell.com/blog/articles/CreatingCustomSharePointTimerJobs.aspx
主要是继承SpJobDefinition,改写几个构造体和Execute的方法.基本代码的模式就是这个样子:
下面是自己的一段代码有些凌乱:
1
class EventCheckTimesSendEmail : SPJobDefinition
2
{
3
public EventCheckTimesSendEmail() : base() { }
4
public EventCheckTimesSendEmail(string _timername, SPWebApplication _wp)
5
: base(_timername, _wp, null, SPJobLockType.ContentDatabase)
6
{
7
this.Title = "SendEmailEventCheckTime";
8
}
9
public override void Execute(Guid targetInstanceId)
10
{
11
//这些参数都是从OwsTimer.exe.config中读取的。这个文件是自己添加的。参数也可以自己写的。
12
SPWebApplication webApplication = this.Parent as SPWebApplication;
13
SPContentDatabase contentDb = webApplication.ContentDatabases[targetInstanceId];
14
string splistname = ConfigurationManager.AppSettings.Get("ListName");
15
string smtpHost = ConfigurationManager.AppSettings.Get("SmtpHost");
16
string smtpName = ConfigurationManager.AppSettings.Get("SmtpName");
17
string smtpPass = ConfigurationManager.AppSettings.Get("SmtpPass");
18
string emailTitle = ConfigurationManager.AppSettings.Get("EmailTitle");
19
string emailContent = ConfigurationManager.AppSettings.Get("EmailContent");
20
string spwebName = ConfigurationManager.AppSettings.Get("SpwebName");
21
SPWeb spweb = contentDb.Sites[0].AllWebs[spwebName];
22
DateTime dt;
23
foreach (SPListItem spli in spweb.Lists[splistname].Items)
24
{
25
string spff = null;
26
27
Stream stream = spli.File.OpenBinaryStream();
28
StreamReader sr = new StreamReader(stream);
29
XmlDocument xd = new XmlDocument();
30
xd.LoadXml(sr.ReadToEnd());
31
XmlNamespaceManager xnm = new XmlNamespaceManager(xd.NameTable);
32
xnm.AddNamespace(xd.DocumentElement.Prefix, xd.DocumentElement.NamespaceURI);
33
//XmlNode xnItemDateLine = xd.SelectSingleNode(ItemDateLine, xnm);
34
XmlNode xncommitteeAcion = xd.SelectSingleNode(committeeAcion, xnm);
35
XmlNode xnsubmissionType=xd.SelectSingleNode(submissionType,xnm);
36
dt = Convert.ToDateTime(xd.SelectSingleNode(ItemDateLine, xnm).InnerText);
37
38
TimeSpan ts;
39
DateTime dtNow = DateTime.Now;
40
string monthsStr = xd.SelectSingleNode(renewal, xnm).InnerText;
41
string toemail = itemEmail.ToString();
42
43
int otherMonthNum = 0;
44
string dateunit=null;
45
if (monthsStr.Equals("Other"))
46
{
47
if (xd.SelectSingleNode(otherRenewal,xnm).InnerText.ToString().Trim() != null)
48
{
49
string DateUnits = xd.SelectSingleNode(ItemDateUnits, xnm).InnerText.ToString();
50
string reOther = xd.SelectSingleNode(otherRenewal, xnm).InnerText.ToString();
51
otherMonthNum = int.Parse(reOther);
52
DateTime dtotherDate;
53
if (DateUnits.Equals("Days"))
54
{
55
dtotherDate = dtNow.AddDays(otherMonthNum);
56
dateunit = "Days";
57
}
58
else if (DateUnits.Equals("Months"))
59
{
60
dtotherDate = dtNow.AddMonths(otherMonthNum);
61
dateunit = "Months";
62
}
63
else if (DateUnits.Equals("Years"))
64
{
65
dtotherDate = dtNow.AddYears(otherMonthNum);
66
dateunit = "Years";
67
}
68
else
69
{ return; }
70
ts = (dt.Date - dtotherDate.Date);
71
}
72
else { return; }
73
}
74
else
75
{
76
//sendEmail time
77
string[] monthss = monthsStr.ToString().Trim().Split('M');
78
otherMonthNum = int.Parse(monthss[0].ToString());
79
DateTime dtMoth = dtNow.AddMonths(otherMonthNum);
80
dateunit = "Months";
81
ts = (dtMoth.Date - dt.Date);
82
}
83
string sateTime = otherMonthNum + " " + dateunit + " mails reply";
84
//if (ts.Days == 0)
85
//{
86
// string to = toemail;
87
// string title = emailTitle;
88
// string content = emailContent + ", This " + otherMonthNum + " " + dateunit + " mails reminds ahead of time";
89
90
// // string returnValues = SendEmial(smtpHost, smtpName, smtpPass, to, title, content);
91
//}
92
if (ts.Days == 0 && xncommitteeAcion.InnerText.ToString().Equals(actionSates) && !xnsubmissionType.InnerText.ToString().Equals(submissionTypeValue.ToString()) && spli["SatesOfTimer"] == null)
93
{
94
//Send Email
95
string to = toemail;
96
string title = emailTitle;
97
string content = emailContent + ", This " + otherMonthNum + " " + dateunit + " mails reminds ahead of time";
98
string returnValues = SendEmial(smtpHost, smtpName, smtpPass, to, title, content);
99
100
//add a listitem
101
if (returnValues.Equals("OK"))
102
{
103
spli["SatesOfTimer"] = otherMonthNum + " " + dateunit + " mails reply";
104
spli.Update();
105
spweb.Update();
106
107
}
108
}
109
else if (ts.Days == 0 && xncommitteeAcion.InnerText.ToString().Equals(actionSates) && !xnsubmissionType.InnerText.ToString().Equals(submissionTypeValue.ToString()) && !spli["SatesOfTimer"].ToString().Equals(sateTime))
110
{
111
//Send Email
112
string to = toemail;
113
string title = emailTitle;
114
string content = emailContent + ", This " + otherMonthNum + " " + dateunit + " mails reminds ahead of time";
115
string returnValues = SendEmial(smtpHost, smtpName, smtpPass, to, title, content);
116
117
//add a listitem
118
if (returnValues.Equals("OK"))
119
{
120
spli["SatesOfTimer"] = otherMonthNum + " " + dateunit + " mails reply";
121
spli.Update();
122
spweb.Update();
123
}
124
}
125
126
}
127
}
128
129
private string SendEmial(string smtpHost, string smtpName, string smtpPass, string to, string title, string content)
130
{
131
MailAddress sendto = new MailAddress(to);
132
MailAddress sendForm = new MailAddress(smtpName);
133
MailMessage _mailMessage = new MailMessage(sendForm, sendto);
134
_mailMessage.Subject = title;
135
_mailMessage.Body = content;
136
_mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
137
SmtpClient _smtpClient = new SmtpClient(smtpHost);
138
_smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
139
_smtpClient.Credentials = new System.Net.NetworkCredential(smtpName, smtpPass);
140
141
try
142
{
143
_smtpClient.Send(_mailMessage);
144
return "OK";
145
}
146
catch (Exception ex)
147
{
148
return ex.Message;
149
}
150
}
151
class EventCheckTimesSendEmail : SPJobDefinition2
{3
public EventCheckTimesSendEmail() : base() { }4
public EventCheckTimesSendEmail(string _timername, SPWebApplication _wp)5
: base(_timername, _wp, null, SPJobLockType.ContentDatabase)6
{7
this.Title = "SendEmailEventCheckTime";8
}9
public override void Execute(Guid targetInstanceId)10
{11
//这些参数都是从OwsTimer.exe.config中读取的。这个文件是自己添加的。参数也可以自己写的。12
SPWebApplication webApplication = this.Parent as SPWebApplication;13
SPContentDatabase contentDb = webApplication.ContentDatabases[targetInstanceId];14
string splistname = ConfigurationManager.AppSettings.Get("ListName");15
string smtpHost = ConfigurationManager.AppSettings.Get("SmtpHost");16
string smtpName = ConfigurationManager.AppSettings.Get("SmtpName");17
string smtpPass = ConfigurationManager.AppSettings.Get("SmtpPass");18
string emailTitle = ConfigurationManager.AppSettings.Get("EmailTitle");19
string emailContent = ConfigurationManager.AppSettings.Get("EmailContent"); 20
string spwebName = ConfigurationManager.AppSettings.Get("SpwebName");21
SPWeb spweb = contentDb.Sites[0].AllWebs[spwebName];22
DateTime dt; 23
foreach (SPListItem spli in spweb.Lists[splistname].Items)24
{25
string spff = null;26
27
Stream stream = spli.File.OpenBinaryStream();28
StreamReader sr = new StreamReader(stream);29
XmlDocument xd = new XmlDocument();30
xd.LoadXml(sr.ReadToEnd());31
XmlNamespaceManager xnm = new XmlNamespaceManager(xd.NameTable);32
xnm.AddNamespace(xd.DocumentElement.Prefix, xd.DocumentElement.NamespaceURI);33
//XmlNode xnItemDateLine = xd.SelectSingleNode(ItemDateLine, xnm);34
XmlNode xncommitteeAcion = xd.SelectSingleNode(committeeAcion, xnm);35
XmlNode xnsubmissionType=xd.SelectSingleNode(submissionType,xnm);36
dt = Convert.ToDateTime(xd.SelectSingleNode(ItemDateLine, xnm).InnerText);37

38
TimeSpan ts;39
DateTime dtNow = DateTime.Now;40
string monthsStr = xd.SelectSingleNode(renewal, xnm).InnerText;41
string toemail = itemEmail.ToString();42

43
int otherMonthNum = 0;44
string dateunit=null;45
if (monthsStr.Equals("Other"))46
{47
if (xd.SelectSingleNode(otherRenewal,xnm).InnerText.ToString().Trim() != null)48
{49
string DateUnits = xd.SelectSingleNode(ItemDateUnits, xnm).InnerText.ToString();50
string reOther = xd.SelectSingleNode(otherRenewal, xnm).InnerText.ToString();51
otherMonthNum = int.Parse(reOther);52
DateTime dtotherDate;53
if (DateUnits.Equals("Days"))54
{55
dtotherDate = dtNow.AddDays(otherMonthNum);56
dateunit = "Days";57
}58
else if (DateUnits.Equals("Months"))59
{60
dtotherDate = dtNow.AddMonths(otherMonthNum);61
dateunit = "Months";62
}63
else if (DateUnits.Equals("Years"))64
{65
dtotherDate = dtNow.AddYears(otherMonthNum);66
dateunit = "Years";67
}68
else69
{ return; }70
ts = (dt.Date - dtotherDate.Date);71
}72
else { return; }73
}74
else75
{76
//sendEmail time77
string[] monthss = monthsStr.ToString().Trim().Split('M');78
otherMonthNum = int.Parse(monthss[0].ToString());79
DateTime dtMoth = dtNow.AddMonths(otherMonthNum);80
dateunit = "Months";81
ts = (dtMoth.Date - dt.Date); 82
}83
string sateTime = otherMonthNum + " " + dateunit + " mails reply";84
//if (ts.Days == 0)85
//{86
// string to = toemail;87
// string title = emailTitle;88
// string content = emailContent + ", This " + otherMonthNum + " " + dateunit + " mails reminds ahead of time";89

90
// // string returnValues = SendEmial(smtpHost, smtpName, smtpPass, to, title, content);91
//}92
if (ts.Days == 0 && xncommitteeAcion.InnerText.ToString().Equals(actionSates) && !xnsubmissionType.InnerText.ToString().Equals(submissionTypeValue.ToString()) && spli["SatesOfTimer"] == null)93
{94
//Send Email95
string to = toemail;96
string title = emailTitle;97
string content = emailContent + ", This " + otherMonthNum + " " + dateunit + " mails reminds ahead of time";98
string returnValues = SendEmial(smtpHost, smtpName, smtpPass, to, title, content);99

100
//add a listitem101
if (returnValues.Equals("OK"))102
{103
spli["SatesOfTimer"] = otherMonthNum + " " + dateunit + " mails reply";104
spli.Update();105
spweb.Update();106

107
}108
}109
else if (ts.Days == 0 && xncommitteeAcion.InnerText.ToString().Equals(actionSates) && !xnsubmissionType.InnerText.ToString().Equals(submissionTypeValue.ToString()) && !spli["SatesOfTimer"].ToString().Equals(sateTime))110
{111
//Send Email112
string to = toemail;113
string title = emailTitle;114
string content = emailContent + ", This " + otherMonthNum + " " + dateunit + " mails reminds ahead of time";115
string returnValues = SendEmial(smtpHost, smtpName, smtpPass, to, title, content);116

117
//add a listitem118
if (returnValues.Equals("OK"))119
{120
spli["SatesOfTimer"] = otherMonthNum + " " + dateunit + " mails reply";121
spli.Update();122
spweb.Update();123
}124
}125

126
}127
}128
129
private string SendEmial(string smtpHost, string smtpName, string smtpPass, string to, string title, string content)130
{131
MailAddress sendto = new MailAddress(to);132
MailAddress sendForm = new MailAddress(smtpName);133
MailMessage _mailMessage = new MailMessage(sendForm, sendto);134
_mailMessage.Subject = title;135
_mailMessage.Body = content;136
_mailMessage.BodyEncoding = System.Text.Encoding.UTF8;137
SmtpClient _smtpClient = new SmtpClient(smtpHost);138
_smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; 139
_smtpClient.Credentials = new System.Net.NetworkCredential(smtpName, smtpPass);140

141
try142
{143
_smtpClient.Send(_mailMessage);144
return "OK";145
}146
catch (Exception ex)147
{148
return ex.Message; 149
}150
} 151

另外一个类就是:
1
class EventCheckTimersInstallerSendEmail : SPFeatureReceiver
2
{
3
const string MY_TASK = "EventCheckTimesSendEmail";
4
public override void FeatureInstalled(SPFeatureReceiverProperties properties)
5
{
6
7
}
8
public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
9
{
10
11
}
12
public override void FeatureActivated(SPFeatureReceiverProperties properties)
13
{
14
SPSite spsite = properties.Feature.Parent as SPSite;
15
16
foreach (SPJobDefinition job in spsite.WebApplication.JobDefinitions)
17
{
18
if (job.Name == MY_TASK)
19
job.Delete();
20
}
21
22
EventCheckTimesSendEmail timer = new EventCheckTimesSendEmail(MY_TASK, spsite.WebApplication);
23
24
//时间写短点是为测试
25
SPMinuteSchedule schedule = new SPMinuteSchedule();
26
schedule.BeginSecond = 0;
27
schedule.EndSecond = 59;
28
schedule.Interval = 59;
29
30
timer.Schedule = schedule;
31
timer.Update();
32
33
}
34
35
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
36
{
37
SPSite spsite = properties.Feature.Parent as SPSite;
38
foreach (SPJobDefinition job in spsite.WebApplication.JobDefinitions)
39
{
40
if (job.Name == MY_TASK)
41
job.Delete();
42
}
43
}
44
}
接下来就是部署这个写好的定时器。
class EventCheckTimersInstallerSendEmail : SPFeatureReceiver2
{3
const string MY_TASK = "EventCheckTimesSendEmail";4
public override void FeatureInstalled(SPFeatureReceiverProperties properties)5
{6

7
}8
public override void FeatureUninstalling(SPFeatureReceiverProperties properties)9
{10

11
}12
public override void FeatureActivated(SPFeatureReceiverProperties properties)13
{14
SPSite spsite = properties.Feature.Parent as SPSite;15

16
foreach (SPJobDefinition job in spsite.WebApplication.JobDefinitions)17
{18
if (job.Name == MY_TASK)19
job.Delete();20
}21

22
EventCheckTimesSendEmail timer = new EventCheckTimesSendEmail(MY_TASK, spsite.WebApplication);23

24
//时间写短点是为测试25
SPMinuteSchedule schedule = new SPMinuteSchedule();26
schedule.BeginSecond = 0;27
schedule.EndSecond = 59;28
schedule.Interval = 59;29

30
timer.Schedule = schedule;31
timer.Update();32
33
}34

35
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)36
{37
SPSite spsite = properties.Feature.Parent as SPSite;38
foreach (SPJobDefinition job in spsite.WebApplication.JobDefinitions)39
{40
if (job.Name == MY_TASK)41
job.Delete();42
}43
}44
}用Stsadm.exe来部署
代码写完了以后,还要写一个Feature,这个Feature比较简单,就一个XML文件
Feature.xml:
<?xml version="1.0" encoding="utf-8" ?>
<Feature xmlns="http://schemas.microsoft.com/sharepoint/"
Id="1F481C17-4FDA-4919-A64A-EAE5C1301B4B"
Title="Image Validation Checker"
Description="If any images in the top level site colleciton images are expiring soon,email relative person."
Scope="Site"
Hidden="TRUE"
Version="1.0.0.0"
ReceiverAssembly="TimerJobControl, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f2aef6a9088f714f"
ReceiverClass="TimerJobControl.ImageValidationCheckerJobInstaller">
</Feature>
剩下的就是把feature装好就好了,假如代码没有出错的话。
至于怎么Debug这个程序,走以下步骤
把Assembly DLL放到GAC
- 命令行:iisreset
- 先Deactivate feature, 然后activate feature.
- 命令行:net stop SPTimerV3
- 命令行:net start SPTimerV3
- Visual Studio: Attach to process: OWSTIMER.EXE
这样就OK了。
浙公网安备 33010602011771号