public class Global : System.Web.HttpApplication
{
private static Logger Log = NLog.LogManager.GetCurrentClassLogger();
public System.Threading.Thread schedulerThread = null;
protected void Application_Start(object sender, EventArgs e)
{
//定义定时器
string UpdateInterval = ConfigurationManager.AppSettings["UpdateInterVal"] == null ? "86400" : ConfigurationManager.AppSettings["UpdateInterVal"].ToString();//更新频率
int Interval = Convert.ToInt32(UpdateInterval) * 1000;
System.Timers.Timer myTimer = new System.Timers.Timer(Interval);
myTimer.Elapsed += new ElapsedEventHandler(myTimer_Elapsed);
myTimer.Enabled = true;
myTimer.AutoReset = true;
}
void myTimer_Elapsed(object source, ElapsedEventArgs e)
{
try
{
YourTask(); //要处理的信息
}
catch (Exception ee)
{
Log.Error(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":AutoTask is Error!错误信息:" + ee.Message);
}
}
void YourTask()
{
//文件保存的物理路径,CSTest为虚拟目录名称,F:\Inetpub\wwwroot\CSTest为物理路径
string p = HttpRuntime.AppDomainAppPath + "\\360";
//我们在虚拟目录的根目录下建立SchedulerJob文件夹,并设置权限为匿名可修改,
//SchedulerJob.txt就是我们所写的文件
string FILE_NAME = p + "\\Job.txt";
//取得当前服务器时间,并转换成字符串
string c = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
//标记是否是新建文件的标量
bool flag = false;
//如果文件不存在,就新建该文件
if (!File.Exists(FILE_NAME))
{
flag = true;
StreamWriter sr = File.CreateText(FILE_NAME);
sr.Close();
}
//调用的方法体
///
//向文件写入内容
StreamWriter x = new StreamWriter(FILE_NAME, true, System.Text.Encoding.Default);
if (flag) x.Write("计划任务测试开始:");
x.Write("\r\n" + c);
x.Close();
}
protected void Session_Start(object sender, EventArgs e)
{
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
}
protected void Application_Error(object sender, EventArgs e)
{
}
protected void Session_End(object sender, EventArgs e)
{
}
protected void Application_End(object sender, EventArgs e)
{
string websitePath = ConfigurationManager.AppSettings["InterFreePath"] == null ? "" : ConfigurationManager.AppSettings["InterFreePath"].ToString();
if (null != schedulerThread)
{
schedulerThread.Abort();
}
Log.Error(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":Application End!");
//下面的代码是关键,可解决IIS应用程序池自动回收的问题
Thread.Sleep(1000);
//这里设置你的web地址,可以随便指向你的任意一个aspx页面甚至不存在的页面,目的是要激发Application_Start
string url = websitePath + "/360/getdata.aspx";
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
Stream receiveStream = myHttpWebResponse.GetResponseStream();//得到回写的字节流
}
}
asp.net Global.asax定时更新
最新推荐文章于 2019-03-15 15:15:00 发布