.net - Windows 服务中定时器的使用

标签 .net windows-services service timer

我有一个 Windows 服务,我想每 10 秒创建一个文件。

我收到很多评论,Windows 服务中的 Timer 将是最佳选择。

我怎样才能做到这一点?

最佳答案

首先,选择正确的计时器。你想要 System.Timers.TimerSystem.Threading.Timer - 不要使用与 UI 框架相关联的框架(例如 System.Windows.Forms.TimerDispatcherTimer )。

定时器通常很简单

  • 设置刻度间隔
  • 将处理程序添加到 Elapsed事件(或在构造时将回调传递给它),
  • 必要时启动计时器(不同的类工作方式不同)

  • 一切都会好起来的。

    sample :
    // System.Threading.Timer sample
    using System;
    using System.Threading;
    
    class Test
    {
        static void Main() 
        {
            TimerCallback callback = PerformTimerOperation;
            Timer timer = new Timer(callback);
            timer.Change(TimeSpan.Zero, TimeSpan.FromSeconds(1));
            // Let the timer run for 10 seconds before the main
            // thread exits and the process terminates
            Thread.Sleep(10000);
        }
    
        static void PerformTimerOperation(object state)
        {
            Console.WriteLine("Timer ticked...");
        }
    }
    
    // System.Timers.Timer example
    using System;
    using System.Threading;
    using System.Timers;
    // Disambiguate the meaning of "Timer"
    using Timer = System.Timers.Timer;
    
    class Test
    {
        static void Main() 
        {
            Timer timer = new Timer();
            timer.Elapsed += PerformTimerOperation;
            timer.Interval = TimeSpan.FromSeconds(1).TotalMilliseconds;
            timer.Start();
            // Let the timer run for 10 seconds before the main
            // thread exits and the process terminates
            Thread.Sleep(10000);
        }
    
        static void PerformTimerOperation(object sender,
                                          ElapsedEventArgs e)
        {
            Console.WriteLine("Timer ticked...");
        }
    }
    

    我有更多关于 this page 的信息,虽然我很久没有更新了。

    关于.net - Windows 服务中定时器的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5495842/

    相关文章:

    .net - UDP负载测试: How do you simulate many UDP clients?

    c# - 如何通过 Unity 容器配置 HttpClient?

    c# - 为什么这个服务是 "not responding to the start or control request in a timely fashion"?

    python - 来自 Python 服务的警报弹出窗口

    c# - 如何将 WCF 服务添加到现有的 winforms 应用程序?

    c# - 在 HttpListener、GetContextAsync 之后使用 Task.Run 或 ContinueWith?

    .net - 为什么/什么时候应该在 .net 中使用嵌套类?或者你不应该吗?

    android - 与 Android 服务对话的状态通知

    c# - 作为系统执行任务?

    c# - 在 Windows 服务启动之间创建依赖关系