现在的位置: 首页 > 综合 > 正文

如何让asp.net的页面(类)定时运行

2013年12月03日 ⁄ 综合 ⁄ 共 10216字 ⁄ 字号 评论关闭

我们有时候写的程序没有前台的页面,只是一个对数据库操作的过程,因为它的操作可能会大量使用数据库。因为它占用的资源比较大,我们一般都会让他在半夜的时候显示。这时候我们可以采用数据库的作业功能。可是有一个问题是,如果我们的这个操作还要从别的网站页面中取得相应的信息后,再进行处理。这怎么办呢。下面就是我采用的方法。

我要完成的功能是这样的,根据我数据库中的IP,到www.ip138.com上取得相应的地址,然后存入数据库中。

下面是我的代码(我建立的是一个类)
这个类是我要运行的代码,你要在Global.asax中运行它

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.UI;
  6. using System.Web.UI.WebControls;
  7. using System.IO;
  8. using System.Text;
  9. using System.Net;
  10. using System.Threading;
  11. using System.Data;
  12. using System.Data.SqlClient;
  13. using System.Collections;
  14. namespace getPageValue
  15. {
  16.     public class TimeRun
  17.     {
  18.         #region 数据库操作
  19.         public string dbType = "0";
  20.         public SqlConnection conn = new SqlConnection("server=.;uid=sa;pwd=123;database=DBCT_Dev");
  21.       
  22.         public SqlCommand cmd;
  23.         public SqlDataAdapter da;
  24.         //关闭所有资源
  25.         public void Reset()
  26.         {
  27.             cmd.Dispose();
  28.             da.Dispose();
  29.             conn.Dispose();
  30.             conn.Close();
  31.         }
  32.         /// <summary>
  33.         /// 根据传入的语句,得到DataSet
  34.         /// </summary>
  35.         /// <param name="strsql"></param>
  36.         /// <returns></returns>
  37.         public DataSet GetDataSet(string strsql)
  38.         {
  39.             //this.Reset();
  40.             cmd = new SqlCommand("", conn);
  41.             cmd.CommandText = strsql;
  42.             DataSet ds = new DataSet();
  43.             da = new SqlDataAdapter();
  44.             da.SelectCommand = cmd;
  45.             da.Fill(ds);
  46.             return ds;
  47.         }
  48.         /// <summary>
  49.         /// 根据传入的语句,得到DataTable
  50.         /// </summary>
  51.         /// <param name="strsql"></param>
  52.         /// <returns></returns>
  53.         public DataTable GetDataTable(string strsql)
  54.         {
  55.             DataSet ds = GetDataSet(strsql);
  56.             return ds.Tables[0];
  57.         }
  58.         /// <summary>
  59.         /// 语句执行删除,插入,修改操作.
  60.         /// </summary>
  61.         /// <param name="strsql"></param>
  62.         /// <returns></returns>
  63.         public bool ExecuteSql(string strsql)
  64.         {
  65.             //this.Reset();
  66.             conn.Close();
  67.             conn.Open();
  68.             cmd = new SqlCommand("", conn);
  69.             cmd.CommandText = strsql;
  70.             return cmd.ExecuteNonQuery() != 0;
  71.         }
  72.         /// <summary>
  73.         /// 根据传入语句,取得相应数量,一般传入值为select count(*) from table
  74.         /// </summary>
  75.         /// <param name="strsql"></param>
  76.         /// <returns></returns>
  77.         public int ExecuteScalarSql(string strsql)
  78.         {
  79.             conn.Open();
  80.             cmd = new SqlCommand("", conn);
  81.             cmd.CommandText = strsql;
  82.             return Convert.ToInt32(cmd.ExecuteScalar());
  83.             //conn.Close();
  84.         }
  85.         /// <summary>
  86.         /// 根据传进来的值,取相应的字段
  87.         /// </summary>
  88.         /// <param name="GetTable">所要查询的表</param>
  89.         /// <param name="GetValue">所要得到的字段值</param>
  90.         /// <param name="Wherestr">条件语句</param>
  91.         /// <returns></returns>
  92.         public string GetSingleValue(string GetTable, string GetValue, string Wherestr)
  93.         {
  94.             string strsql = "select " + GetValue + " from " + GetTable + " where " + Wherestr + "";
  95.             DataTable dt = this.GetDataTable(strsql);
  96.             if (dt.Rows.Count > 0)
  97.                 return dt.Rows[0][0].ToString();
  98.             else
  99.                 return "无信息";
  100.         }
  101.         #endregion
  102.         private static ManualResetEvent allDone = new ManualResetEvent(false);
  103.         public static string singleip;
  104.         private static readonly TimeRun _ScheduledTask = null;
  105.         private System.Threading.Timer UpdateTimer = null;
  106.         //间隔时间,这里设置为15分钟
  107.         private int Interval = 15 * 60000;
  108.         private int _IsRunning;
  109.         static TimeRun()
  110.         {
  111.             _ScheduledTask = new TimeRun();
  112.         }
  113.         public static TimeRun Instance()
  114.         {
  115.             return _ScheduledTask;
  116.         }
  117.         public void Start()
  118.         {
  119.             if(UpdateTimer == null)
  120.             {
  121.                 UpdateTimer = new System.Threading.Timer(new System.Threading.TimerCallback(UpdateTimerCallback), null, Interval, Interval);
  122.             }
  123.         }
  124.         private void UpdateTimerCallback(object sender)
  125.         {
  126.             if(Interlocked.Exchange(ref _IsRunning, 1) == 0)
  127.             {
  128.                 try
  129.                 {
  130.                     //此处写你自己想执行的任务
  131.                     if (DateTime.Now.ToShortTimeString() == "10:51")
  132.                     {
  133.                         //将数据库中Code为空ip不为空的记录存入,放到一个DataTable中。
  134.                         string strsql = "select top 30 * from UserCode where UserIP<>'' and (Code is null or code = '')";
  135.                         DataTable dt = GetDataTable(strsql);
  136.                         for (int i = 0; i < dt.Rows.Count; i++)
  137.                         {
  138.                             //调用转化方法
  139.                             getPost(dt.Rows[i]["id"].ToString());
  140.                             //每次调用间隔一秒,通过实验得到,如果你的数据量大,最好间隔5秒
  141.                             Thread.Sleep(5000);
  142.                         }
  143.                         dt.Dispose();
  144.                     }
  145.                 }
  146.                 catch(Exception ex)
  147.                 {
  148.                 }
  149.                 finally
  150.                 {
  151.                     Interlocked.Exchange(ref _IsRunning, 0);
  152.                 }
  153.             }
  154.         }
  155.         public void Stop()
  156.         {
  157.             if(UpdateTimer != null)
  158.             {
  159.                 UpdateTimer.Dispose();
  160.                 UpdateTimer = null;
  161.             }
  162.         }
  163.         public void getPost(string id)
  164.         {
  165.             //singleid 传入的用户信息ID
  166.             //singleip 根据用户信息ID,而取到的IP
  167.             //strAction post必传值之一
  168.             //strCode 传入用户信息表中的code值
  169.             string singleid = id;
  170.             //通过GetSingleValue方法,得到相应的值,这里GetSingleValue(表名,要得到的值,条件语句)
  171.             singleip = GetSingleValue("UserCode""UserIP""id=" + singleid).Trim();
  172.             //建立HttpWebRequest
  173.             HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://www2.ip138.com/ips8.asp");
  174.             myRequest.Method = "POST";
  175.             myRequest.ContentType = "application/x-www-form-urlencoded";
  176.             //开始调用异步操作
  177.             myRequest.BeginGetRequestStream(new AsyncCallback(ReadCallback), myRequest);
  178.             allDone.WaitOne();
  179.             //异步回调方法使用 EndGetResponse 方法返回实际的 WebResponse。 
  180.             HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse();
  181.             Stream streamResponse = response.GetResponseStream();
  182.             StreamReader streamRead = new StreamReader(streamResponse, Encoding.Default);
  183.             string content = streamRead.ReadToEnd();
  184.             streamResponse.Close();
  185.             streamRead.Close();
  186.             response.Close();
  187.             //判断是否是有省市的信息,如果信息中有省,市,则进行存入数据库。其它信息,则为0035进入其它
  188.             //string singleip = "";
  189.             string strCode = "";
  190.             if (singleip == "127.0.0.1")
  191.             {
  192.                 strCode = "0008";
  193.             }
  194.             else
  195.             {
  196.                 if (content.IndexOf("省") == -1 && content.IndexOf("市") == -1 && singleid != "127.0.0.1")
  197.                 {
  198.                     if (content.IndexOf("查询太频繁") != -1)
  199.                     {
  200.                         strCode = "查询太频繁";
  201.                     }
  202.                     else
  203.                     {
  204.                         strCode = "0035";
  205.                     }
  206.                 }
  207.                 else
  208.                 {
  209.                     if (content.IndexOf("省") != -1)
  210.                     {
  211.                         string con = content.Substring(content.IndexOf("本站主数据") + 6, content.IndexOf("</li><li>参考数据一") - content.IndexOf("本站主数据") - 1);
  212.                         string strpro = con.Substring(0, con.IndexOf("省") + 1);
  213.                         strCode = GetSingleValue("S_Province""ProvinceCode""ProvinceName='" + strpro + "'").Trim();
  214.                         //strCode = strpro;
  215.                     }
  216.                     if (content.IndexOf("市") != -1)
  217.                     {
  218.                         string con = content.Substring(content.IndexOf("本站主数据") + 6, content.IndexOf("</li><li>参考数据一") - content.IndexOf("本站主数据") - 1);
  219.                         string strpro = con.Substring(con.IndexOf("省") + 1, con.IndexOf("市") - con.IndexOf("省"));
  220.                         strCode += GetSingleValue("S_City""ZipCode""CityName='" + strpro + "'").Trim(); ;
  221.                     }
  222.                 }
  223.             }
  224.             if (strCode == "")
  225.             {
  226.                 strCode = "0035";
  227.             }
  228.             //将信息存入hashtable
  229.             string strsql = "update UserCode set Code='" + strCode + "' where id=" + id + "";
  230.             try
  231.             {
  232.                 ExecuteSql(strsql);
  233.             }
  234.             catch
  235.             {
  236.             }
  237.         }
  238.         private void ReadCallback(IAsyncResult asynchronousResult)
  239.         {
  240.             try
  241.             {
  242.                 HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
  243.                 Stream postStream = request.EndGetRequestStream(asynchronousResult);
  244.                 ASCIIEncoding encoding = new ASCIIEncoding();
  245.                 string postData = "ip=" + singleip;
  246.                 postData += "&action=2";
  247.                 byte[] data = encoding.GetBytes(postData);
  248.                 postStream.Write(data, 0, postData.Length);
  249.                 postStream.Close();
  250.                 allDone.Set();
  251.             }
  252.             catch
  253.             { return; }
  254.         }
  255.         
  256.     }
  257. }

  Global.asax文件中的代码

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Security;
  6. using System.Web.SessionState;
  7. using System.Timers;
  8. namespace getPageValue
  9. {
  10.     
  11.     public class Global : System.Web.HttpApplication
  12.     {
  13.         protected void Application_Start(object sender, EventArgs e)
  14.         {
  15.             TimeRun.Instance().Start();
  16.         }
  17.         private void mess(object sender, ElapsedEventArgs e)
  18.         {
  19.             TimeRun.Instance().Stop();
  20.         }
  21.         protected void Session_Start(object sender, EventArgs e)
  22.         {
  23.         }
  24.         protected void Application_BeginRequest(object sender, EventArgs e)
  25.         {
  26.         }
  27.         protected void Application_AuthenticateRequest(object sender, EventArgs e)
  28.         {
  29.         }
  30.         protected void Application_Error(object sender, EventArgs e)
  31.         {
  32.         }
  33.         protected void Session_End(object sender, EventArgs e)
  34.         {
  35.         }
  36.         protected void Application_End(object sender, EventArgs e)
  37.         {
  38.         }
  39.     }
  40. }

抱歉!评论已关闭.