【问题标题】:Solution to run a .NET component on regular intervals in Windows在 Windows 中定期运行 .NET 组件的解决方案
【发布时间】:2011-03-22 21:58:40
【问题描述】:

我需要编写一些定期运行的 .NET 代码来检查数据库中表中的“未处理”项目,对其进行处理,然后将它们写回数据库以进行处理。我们可能会将其设置为每分钟运行一次。

如何在 Windows Server 环境中的组件中进行设置,以便代码定期执行?

【问题讨论】:

    标签: windows windows-services scheduling


    【解决方案1】:

    在您的 Windows 服务中使用 System.Timers.Timer

    您可以在 Windows 服务 OnStart 事件中包含这样的代码(来自 MSDN):

    // Hook up the Elapsed event for the timer.
    timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
    
    // Set the Interval to 2 seconds (2000 milliseconds).
    timer.Interval = 2000;
    timer.Enabled = true;
    
    ...........
    
    // Specify what you want to happen when the Elapsed event is raised.
    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        ......
    }
    

    如果间隔不频繁,例如每天运行,也可以考虑使用Windows Task Scheduler。它可以在给定的时间间隔内运行您的应用程序(注意该时间间隔是否如此频繁)。

    【讨论】:

      【解决方案2】:

      通过 Windows 任务计划程序创建计划任务。然后,计划任务将定期运行您编译的 .NET EXE(我假设它是一个 EXE)。如果您需要它运行不到一分钟,我认为您需要转移到 Windows 服务。

      【讨论】:

        【解决方案3】:

        Windows 计划任务(启动-程序-附件-系统工具)...SSIS 作业计划...第 3 方作业软件(Activebatch 等)...

        【讨论】:

          【解决方案4】:

          您可以将其设置为一个带有计时器的服务,该计时器会在您需要时随时响起(对于这个频率,这可能是您的最佳选择),或者您可以在 Windows Scheduler 中设置计划任务。

          如果您使用 Windows 服务路由,您的 Start() 方法将类似于:

          Timer tmr = new Timer(60000, true) //this could be wrong: set it for one minute and turn on auto-reset.
          
          tmr.Start();
          

          然后您将有一个事件处理程序来处理计时器的事件(现在不记得名称:Tick,也许?)它将调用您的实际代码。

          如果您的代码完成时间超过一分钟,您可以将自动重启设置为 false,然后在处理部分将控制权交还给服务时重新启用您的计时器。

          【讨论】:

            猜你喜欢
            • 2013-05-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-03-27
            • 1970-01-01
            相关资源
            最近更新 更多