要求:web程序每天定时2:00 删除不需要的日志(也就是数据表里的一些记录),我知道在数据库中可以实现,这个我也会。小弟基本没用过线程,对多线程知道的也很少,想请教各位前辈们指点指点,最好能给写点基础代码,谢谢。我的思路是在Application_start 中定义一个线程,然后这个线程一直处于被唤醒状态,每当时间到2点是该线程被唤醒,执行代码,然后又处于等待状态,可不知道怎么写。

解决方案 »

  1.   


        void Application_Start(object sender, EventArgs e)
        {
    long dueTime = (long)(26 * 3600 - DateTime.Now.TimeOfDay.TotalSeconds) % (24 * 3600) * 1000;
    Application["Timer1"] = new System.Threading.Timer(ClearDatabaseLog, null, dueTime,, 24*3600*1000);
        } void ClearDatabaseLog(object state)
    {
                         ...
    }
      

  2.   

    web应用程序会因为各种原因停止运行,比如闲置超时,所以用线程或时钟不是最好的办法,好的办法是做成Windows服务,当然要麻烦点,部署时也要有服务器的相应权限。
      

  3.   

    不要在web程序中做这个。因为IIS中有设置,默认是如果20分钟没有request,host的进程就会被终止,最好还是写个windows service来做这个吧。
      

  4.   

    SQLServer定时作业job的设置方法. google一下吧
      

  5.   

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Threading;namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback(Dofun), null);        }        static AutoResetEvent av = new AutoResetEvent(false);        public static void Dofun(object obj)
            {
                while (true)
                {
                    av.WaitOne(1000000, false);
                    // Synchronize database
                }
            }
        }
    }