本文介绍了Windows服务中定时器的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a windows service where in I want to create a file every 10 seconds.

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

I got many reviews that Timer in Windows service would be the best option.

我怎样才能做到这一点?

How can I achieve this?

推荐答案

首先,选择合适的计时器类型.您需要 System.Timers.TimerSystem.Threading.Timer - 不要使用与 UI 框架相关联的框架(例如 System.Windows.Forms.定时器DispatcherTimer).

Firstly, pick the right kind of timer. You want either System.Timers.Timer or System.Threading.Timer - don't use one associated with a UI framework (e.g. System.Windows.Forms.Timer or DispatcherTimer).

定时器通常很简单

  1. 设置滴答间隔
  2. Elapsed 事件添加处理程序(或在构造时传递回调),
  3. 如有必要,启动计时器(不同的类工作方式不同)
  1. set the tick interval
  2. Add a handler to the Elapsed event (or pass it a callback on construction),
  3. Start the timer if necessary (different classes work differently)

一切都会好起来的.

示例:

// 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...");
    }
}

我有关于这个页面的更多信息,虽然我好久没更新了.

I have a bit more information on this page, although I haven't updated that for a long time.

这篇关于Windows服务中定时器的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 07:03