日期:2014-05-18  浏览次数:20447 次

怎么编写一个运行在服务端的程序,定时统计数据库
怎么编写一个运行在服务端的程序,定时统计数据库

------解决方案--------------------
vbs?
或者Application_Start里面写timer?
------解决方案--------------------
怎么编写一个运行在服务端的程序,定时统计数据库

好写

写一个服务,定时统计就ok。


难的是客户端定时统计。得用js得timer。或者定时刷页面(累死服务器)
------解决方案--------------------
1.用sql server的作业 2. void Application_Start(object sender, EventArgs e) { // 在应用程序启动时运行的代码 System.Timers.Timer tm = new System.Timers.Timer(); tm.Interval = 3000; tm.Enabled = true; tm.Elapsed += new System.Timers.ElapsedEventHandler(tm_Elapsed); } void tm_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { //你的代码 } 3.windows程序或windows服务
------解决方案--------------------
给你个timer的例子~ 在global.asax里面写。

Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
' 在应用程序启动时激发
' 创建一个计时器,单位:毫秒
Dim aTimer As New System.Timers.Timer(1800000)

' 将 Fresher 指定为计时器的 Elapsed 事件处理程序
AddHandler aTimer.Elapsed, AddressOf CheckWaiting

' AutoReset 属性为 true 时,每隔指定时间循环一次;
' 如果为 false,则只执行一次。
aTimer.AutoReset = True
aTimer.Enabled = True
End Sub

Sub CheckWaiting()
...
End Sub
------解决方案--------------------
用服务器端的timer来解决。

当时比较匆忙没来得及优化,水平也很有限,如果大家觉得某些地方不对或者有更好的方式来解决,还请不吝赐教。

我觉得整个过程两个重点:

如何处理timer
将读取rss模块化,更方便调用
1.关于timer,当然是写在了Global.asax中,首先建立变量:

System.Timers.Timer t=new System.Timers.Timer(1000*Convert.ToInt16(System.Configuration.ConfigurationSettings.AppSettings[ "do_time "]));
其中在web.config 中用do_time来存取多久执行一次

接下来在Application_Start中处理:

t.AutoReset=true;
t.Enabled=true;
if(common.func.get_key( "can_do ")== "1 ")//也是在web.config中存取是否进行定时处理,其中common.func.get_key是自定义的获取设置的函数
t.Elapsed +=new System.Timers.ElapsedEventHandler(fun);
函数fun的代码:


private void fun(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
System.DateTime dt=System.DateTime.Now;
common.func.write_log( "开始读取远程XML ");//写入日志

rss2sql rl=new rss2sql();
rl.readall();
System.DateTime dt2=System.DateTime.Now;
common.func.write_log( "XML文件导入到数据库成功 "+Convert.ToString(dt2-dt));//将本次执行时间写入日志,
}
catch(Exception ex)
{
common.func.write_log( "读取远程xml文件出现错误: "+ex.Message);//写入日志
}
}


Global.asax中代码完毕

2.接下来就是在rss2sql类中从数据库获取rss列表,根据上次读取rss时间和rss文件的修改时间来读取rss文件并写到数据库中,因为用到了太多自定义的类和方法,所以不列出所有的代码,有兴趣的朋友可以到最后下载,其中比较重要的函数:

/**//// <summary>
/// 读取指定链接的rss内容到数据库
/// </summary>
/// <param name= "id "> 对应博客的id </param>
/// <param name= "url "> rss地址 </param>
/// <param name= "dt "> 上次读取时间 </param>
public void read_from_url(string id,string url,System.DateTime dt)
{
op_db.db_class db1=new op_db.db_class();
try
{
rssFeed feed = new rssFeed(url,dt);//建立一个rss读取类实例
feed.read();//开始读取
if(feed.Channel.Items.Count> 0)//如果文章数大于0,开始读取到数据库
{
for(int i=0;i <feed.Channel.Items.Count;i++)
{

write_artical(id,feed.Channel.Items[i].title,feed.Channel.Items[i].link,feed.Channel.Items[i].description,feed.Channel.Items[i].pubDat