asp.net网站每天指定时间执行一项任务

经网上资料搜索和自己测试使用,可以满足需求,如果朋友们发现有问题,请指出,谢谢。        案例达到的功能:每天10点左右自动打开百度网站。
        主要代码:
    1, Global.asax 文件
    
    [cpp]
    void Application_Start(object sender, EventArgs e) 
    { 
        OpenBaiDu.Execute(); 
    } 
            void Application_Start(object sender, EventArgs e)
            {
                OpenBaiDu.Execute();
            }
    2,OpenBaiDu静态类文件
    
    [csharp]
    public static class OpenBaiDu 
    { 
        public static bool IsOpen = false; 
        public static DateTime LastOpenTime = DateTime.Now; 
        public static DateTime OpenTime = DateTime.Today.AddHours(10); 
     
        public static void Execute() 
        { 
            Timer objTimer = new Timer(); 
            objTimer.Interval = 1000; //这个时间单位毫秒,比如10秒,就写10000   
            objTimer.Enabled = true; 
            objTimer.Elapsed += new ElapsedEventHandler(objTimer_Elapsed);  
        } 
     
        public static void objTimer_Elapsed(object sender, ElapsedEventArgs e) 
        { 
            //如果上一次执行时间为昨天,就设置IsOpen为false,说明今天还没有执行  
            if (DateTime.Today.AddDays(-1) == LastOpenTime.Date) 
            { 
                IsOpen = false; 
            } 
            //如果今天还没执行,并且当前时间大于指定执行时间,就执行,  
            //执行完后,设置IsOpen为true,说明今天已执行过了。  
            if (!IsOpen && DateTime.Now >= OpenTime) 
            { 
                System.Diagnostics.Process.Start("http://www.baidu.com"); 
                IsOpen = true; 
                OpenTime = DateTime.Today; 
            } 
     
        }  
    } 
        public static class OpenBaiDu
        {
            public static bool IsOpen = false;
            public static DateTime LastOpenTime = DateTime.Now;
            public static DateTime OpenTime = DateTime.Today.AddHours(10);
            public static void Execute()
            {
                Timer objTimer = new Timer();
                objTimer.Interval = 1000; //这个时间单位毫秒,比如10秒,就写10000
                objTimer.Enabled = true;
                objTimer.Elapsed += new ElapsedEventHandler(objTimer_Elapsed);
            }
            public static void objTimer_Elapsed(object sender, ElapsedEventArgs e)
            {
                //如果上一次执行时间为昨天,就设置IsOpen为false,说明今天还没有执行
                if (DateTime.Today.AddDays(-1) == LastOpenTime.Date)
                {
                    IsOpen = false;
                }
                //如果今天还没执行,并且当前时间大于指定执行时间,就执行,
                //执行完后,设置IsOpen为true,说明今天已执行过了。
                if (!IsOpen && DateTime.Now >= OpenTime)
                {
                    System.Diagnostics.Process.Start("http://www.baidu.com");
                    IsOpen = true;
                    OpenTime = DateTime.Today;
                }
            }
        }

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Grow your business fast with

Suku