今天,我们已经构建了一个控制台应用程序,用于运行我们的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
    }

其他回答

Jeff Atwood为Stackoverflow开发的这个技术是我遇到过的最简单的方法。它依赖于ASP中内置的“缓存项删除”回调机制。NET的缓存系统

更新:Stackoverflow已经超越了这种方法。它只在网站运行时起作用,但这是一个非常简单的技术,对许多人都有用。

也可以看看Quartz。网

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,在出现问题时发送警报消息。

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

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

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

一种选择是设置一个windows服务,让它调用你的计划任务。

在winforms中,我使用了计时器,不认为这将在ASP中很好地工作。网

使用Windows调度器运行网页。

为了防止恶意用户或搜索引擎蜘蛛运行它,当您设置计划任务时,只需使用查询字符串调用web页面,即:mypage.aspx?从= scheduledtask

然后在页面加载时,只需使用一个条件: 如果请求。查询string["from"] == "scheduledtask") { / / executetask }

这样,任何搜索引擎爬行器或恶意用户都无法执行您的计划任务。