C#创建windows服务实例与.NET定时访问数据库案例(2)
实例化记时器类启动后,将在指定时间间隔触发Elapsed指定事件,如上GetSettings为读取我App.config文件里一个配置节点(值为30)的方法,所以上面将会每隔30秒调用TimeOut方法.而改方法就是我们发短信的具体操作.代码如下:
private void TimeOut(object sender, EventArgs e)
{
try
{
if (GetSettings("Enabled").ToLower() == "true")
{
SqlConnection con = new SqlConnection(GetSettings("ConnString"));
SqlCommand cmd = new SqlCommand("select [sysid],[admin_inner_code],[user_inner_code],[phone],[message],[sendtime] from [tbl_note_outbox]", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string phone = rdr["phone"].ToString();
string message = rdr["message"].ToString();
string sendtime = rdr["sendtime"].ToString();
System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("GB2312");
string url = string.Format("http://211.155.23.205/isapi.dll?SendSms&AgentID={0}&PassWord={1}&phone={2}&msg={3}&sendtime={4}", GetSettings("AgentID"), GetSettings("PassWord"), phone,System.Web.HttpUtility.UrlEncode( message,encoder), sendtime);
System.Net.WebClient wClient = new System.Net.WebClient();
string msg = System.Text.Encoding.Default.GetString(wClient.DownloadData(url));
wClient.Dispose();
//删除已经发送成功的,并保存发送记录
if (msg == "发送成功")
{
DateTime dtsend = sendtime == "0" ? DateTime.Now : DateTime.ParseExact(sendtime, "yyyyMMddHHmmss", null);
string sql = string.Format("delete from [tbl_note_outbox] where [sysid]={0} INSERT INTO [tbl_note_log] ([admin_inner_code],[user_inner_code],[status],[phone],[message],[sendtime]) VALUES('{1}','{2}','{3}','{4}','{5}','{6}')", rdr["sysid"], rdr["admin_inner_code"], rdr["user_inner_code"], msg, phone, message, dtsend);
SqlConnection conn = new SqlConnection(GetSettings("ConnString"));
SqlCommand delete = new SqlCommand(sql, conn);
conn.Open();
delete.ExecuteNonQuery();
conn.Close();
delete.Dispose();
}
}
rdr.Close();
con.Close();
cmd.Dispose();
}
}
catch (Exception ex)
{
string errorPath = CurrentPath + "Log\\error.log";
if (!File.Exists(errorPath))
{
FileStream create = File.Create(errorPath);
create.Close();
}
FileStream fs = new FileStream(errorPath, FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine("Exception: " +ex.Message+" --"+ DateTime.Now.ToString());
sw.Flush();
sw.Close();
fs.Close();
}
}
上面我们使用try、catch访问数据库,并记录错误异常信息. 发送短信是使用发送一个Web请求发送出去的,要注意请求url字符串的编码类型,要与请求页面编码一致,不然会出现乱码.上面我们请求的是智网通集团短信(网址:http://www.09168.net/)的Web接口,通过访问他的网站来实现发短信,当然还要传递一些用户名、密码、手机号码和要发送的短信息等参数.他的收费平均大概为7分/条的样子,其实我原本不想用发送Web请求的这样方式来发送短信的,它本身提供了调用它发送短信的DLL,而且还有vc、delphi调用的Demo,但是没有用C#调用的例子,我刚开始试着用非托管动态链接库他提供的DLL,不知方法调用那里出错了一直都没能成功发送出短信,所以后来就用了他的Web方式接口了.他页面直接返回发送短信的状态信息.返回发送成功则短信发送成功,成功后我再将此条信息从要发送短信表里删除并保存在发送记录表里面,以备日后方便查询.其实登陆他的官网进入后台也能方便的查询,