今天,我们已经构建了一个控制台应用程序,用于运行我们的ASP计划任务。网的网站。但是我认为这种方法容易出错,而且很难维护。如何执行计划任务(在windows/IIS/ASP。网络环境)

更新:

任务示例:

从数据库中的电子邮件队列发送电子邮件 从数据库中删除过时的对象 从谷歌AdWords检索统计数据,并在数据库中填充一个表。


当前回答

为什么要重新发明轮子,使用Threading和Timer类。

    protected void Application_Start()
    {
        Thread thread = new Thread(new ThreadStart(ThreadFunc));
        thread.IsBackground = true;
        thread.Name = "ThreadFunc";
        thread.Start();
    }

    protected void ThreadFunc()
    {
        System.Timers.Timer t = new System.Timers.Timer();
        t.Elapsed += new System.Timers.ElapsedEventHandler(TimerWorker);
        t.Interval = 10000;
        t.Enabled = true;
        t.AutoReset = true;
        t.Start();
    }

    protected void TimerWorker(object sender, System.Timers.ElapsedEventArgs e)
    {
        //work args
    }

其他回答

如果你拥有服务器,你应该使用windows任务调度程序。使用AT /?从命令行查看选项。

否则,在基于web的环境中,您可能不得不做一些讨厌的事情,比如设置一台不同的机器,以定时间隔向某个页面发出请求。

我们也使用控制台应用程序。如果您使用像Log4net这样的日志工具,您可以正确地监视它们的执行。另外,我不确定它们为什么比网页更难维护,因为如果设计得当,两者之间可能会共享一些相同的代码库。

如果你不愿意让这些任务定时运行,你可以在你网站的管理部分设置一个网页作为队列。用户输入一个运行任务的请求,它反过来在MyProcessQueue表中插入一个空白的日期戳记录,您的计划任务每X分钟检查一次MyProcessQueue中的新记录。这样,它只在客户希望它运行时运行。

希望这些建议能有所帮助。

为什么要重新发明轮子,使用Threading和Timer类。

    protected void Application_Start()
    {
        Thread thread = new Thread(new ThreadStart(ThreadFunc));
        thread.IsBackground = true;
        thread.Name = "ThreadFunc";
        thread.Start();
    }

    protected void ThreadFunc()
    {
        System.Timers.Timer t = new System.Timers.Timer();
        t.Elapsed += new System.Timers.ElapsedEventHandler(TimerWorker);
        t.Interval = 10000;
        t.Enabled = true;
        t.AutoReset = true;
        t.Start();
    }

    protected void TimerWorker(object sender, System.Timers.ElapsedEventArgs e)
    {
        //work args
    }

这个图书馆非常好用 http://www.codeproject.com/KB/cs/tsnewlib.aspx

它允许您通过. net代码直接管理Windows计划任务。

All of my tasks (which need to be scheduled) for a website are kept within the website and called from a special page. I then wrote a simple Windows service which calls this page every so often. Once the page runs it returns a value. If I know there is more work to be done, I run the page again, right away, otherwise I run it in a little while. This has worked really well for me and keeps all my task logic with the web code. Before writing the simple Windows service, I used Windows scheduler to call the page every x minutes.

另一种方便的运行方法是使用像Pingdom这样的监视服务。将他们的http检查指向运行您的服务代码的页面。让页面返回结果,然后可以使用该结果触发Pingdom,在出现问题时发送警报消息。