ASP.NET Web Service定时执行任务

 

1、首先创建 Global.asax文件
点击Web站点>>添加新建项>>全局应用程序类,即可添加Global.asax文件。

Global.asax文件创建后打开默认有以下方法

Application_Start:在程序初始化的时候执行。在Web应用程序的生命周期里就执行一次,这里只能放一些公用的信息,比如HttpApplicationState。
Session_Start:会话开始时执行。 
Application_BeginRequest:BeginRequest是在收到Request时第一个触发的事件,这个方法第一个执行。 
Application_AuthenticateRequest:当安全模块已经建立了当前用户的标识后执行。 
Application_Error:所有没有处理的错误都会导致这个方法的执行 
Session_End:会话结束或过期时执行。 
Application_End:应用程序结束时,在最后一个HttpApplication销毁之后执行。对应Application_Start,在整个生命周期里面也是只执行一次。 

 

 

2、创建定时任务 有两种方法 使用TimerThread

 protected void Application_Start(object sender, EventArgs e)
{
    //Timer
    System.Timers.Timer myTimer = new System.Timers.Timer();
    myTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimedEvent);
    myTimer.Interval = 60000;//60秒
    myTimer.Enabled = true;
}

 protected void Application_End(object sender, EventArgs e)
{
    WriteInfoLog("Application End!");
}


//Timer
private static void OnTimedEvent(object source, System.Timers.ElapsedEventArgs e)
{
    WriteInfoLog("定时任务启动");
    try
    {
        //执行方法
    } catch (Exception ex)
    {
        WriteInfoLog(ex.Message);
    }
}

 protected void Application_Start(object sender, EventArgs e)
{ 
    //Thread
    thread = new Thread(new ThreadStart(InOut));
    thread.Name = "线程名称";
    thread.Start();
}

 protected void Application_End(object sender, EventArgs e)
{
    WriteInfoLog("Application End!");
}


//Thread
void InOut()
{
    while (true)
    {
        WriteInfoLog("定时任务启动");
        try
        {
            //执行方法
        }catch (Exception ex)
        {
            WriteInfoLog(ex.Message);
        }
        Thread.CurrentThread.Join(1000 * 180);//阻止180秒
    }
}

问题:定时任务执行一段时间后就不在执行

原因:IIS的应用程序池回收

解决方法

目前写了BAT,在Windows 的任务计划程序定时执行 

//拿谷歌浏览器举例
//使用chrome浏览器访问webservice地址 界面打开后暂停10s 关闭chrome浏览器 

@echo off

start chrome.exe http://webservice地址

choice /t 10 /d y /n >nul  

taskkill /f /im chrome.exe

 

这边任务计划程序的创建就不细说了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值