在Windows服务使用定时器 [英] Use of Timer in Windows Service

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

问题描述

我有一个窗口服务,凡在我想创建一个文件,每10秒。

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

我得到了许多评论,定时器在Windows服务将是最好的选择。

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

我怎样才能做到这一点?

How can I achieve this?

推荐答案

首先,挑选合适的计时器。你想要么 System.Timers.Timer的 System.Threading.Timer - 不要使用一个与用户界面相关的框架(如 System.Windows.Forms.Timer 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. 添加处理程序的已用事件(或通过它构建一个回调),
  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服务使用定时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆