Windows服务中Timer组件

本文详细解释了如何在Windows服务中使用基于服务器的Timer组件,并提供了实例代码和注意事项,帮助开发者实现定时任务。

http://www.cnblogs.com/whitewolf/archive/2010/08/25/1808002.html

制作Windows服务时候的Timer控件并不是在工具箱上直接拖拽过来的Timer,那是System.Windows.Forms命名空间下的组件,而我们这里使用的Timer应该是System.Timers.Timer.

  解决方法有:

打开"工具箱"---右键---"选择项"---找到Timer控件,看好了,这个Timer控件的是system.Timer下的.可不是System.Windows.Form.然后添加.

 

我选择的是直接用code书写初始化代码。因为添加项速度真的太慢了,呵呵。

MSDN上关于Timer如下:

 

Timer 组件是基于服务器的计时器,它使您能够指定在应用程序中引发 Elapsed 事件的周期性间隔。然后可以操控此事件以提供定期处理。例如,假设您有一台关键性服务器,必须每周 7 天、每天 24 小时都保持运行。可以创建一个使用 Timer 的服务,以定期检查服务器并确保系统开启并在运行。如果系统不响应,则该服务可以尝试重新启动服务器或通知管理员。

基于服务器的 Timer 是为在多线程环境中用于辅助线程而设计的。服务器计时器可以在线程间移动来处理引发的 Elapsed 事件,这样就可以比 Windows 计时器更精确地按时引发事件。有关基于服务器的计时器的更多信息,请参见“基于服务器的计时器介绍”。

基于 Interval 属性的值,Timer 组件引发 Elapsed 事件。可以处理该事件以执行所需的处理。例如,假设您有一个联机销售应用程序,它不断向数据库发送销售订单。编译发货指令的服务分批处理订单,而不是分别处理每个订单。可以使用 Timer 每 30 分钟启动一次批处理。

Note注意

AutoReset 设置为 false 时,Timer 只在第一个 Interval 过后引发一次 Elapsed 事件。若要保持以 Interval 时间间隔引发 Elapsed 事件,请将 AutoReset 设置为 true

Elapsed 事件在 ThreadPool 线程上引发。如果 Elapsed 事件的处理时间比 Interval 长,在另一个 ThreadPool 线程上将会再次引发���事件。因此,事件处理程序应当是可重入的。

Note注意

在一个线程调用 Stop 方法或将 Enabled 属性设置为 false 的同时,可在另一个线程上运行事件处理方法。这可能导致在计时器停止之后引发 Elapsed 事件。Stop 方法的示例代码演示了一种避免此争用条件的方法。

如果和用户界面元素(如窗体或控件)一起使用 Timer,请将包含有 Timer 的窗体或控件赋值给 SynchronizingObject 属性,以便将此事件封送到用户界面线程中。

Timer 在运行时是不可见的。

示例


下面的示例创建一个 Timer,它每隔五秒钟在控制台上显示一次“Hello World!”。

 

复制代码
代码
using  System;
using  System.Timers;

public   class  Timer1
{
    
public   static   void  Main()
    {
        
//  Normally, the timer is declared at the class level, so
        
//  that it doesn't go out of scope when the method ends.
        
//  In this example, the timer is needed only while Main 
        
//  is executing. However, KeepAlive must be used at the
        
//  end of Main, to prevent the JIT compiler from allowing 
        
//  aggressive garbage collection to occur before Main 
        
//  ends.
        System.Timers.Timer aTimer  =   new  System.Timers.Timer();

        
//  Hook up the Elapsed event for the timer.
        aTimer.Elapsed  +=   new  ElapsedEventHandler(OnTimedEvent);

        
//  Set the Interval to 2 seconds (2000 milliseconds).
        aTimer.Interval  =   2000 ;
        aTimer.Enabled 
=   true ;
 
        Console.WriteLine(
" Press the Enter key to exit the program. " );
        Console.ReadLine();

        
//  Keep the timer alive until the end of Main.
        GC.KeepAlive(aTimer);
    }
 
    
//  Specify what you want to happen when the Elapsed event is 
    
//  raised.
     private   static   void  OnTimedEvent( object  source, ElapsedEventArgs e)
    {
        Console.WriteLine(
" Hello World! " );
    }
}
### 如何在C# Windows服务中实现和配置Timer #### 使用`System.Threading.Timer` 对于Windows服务而言,推荐使用`System.Threading.Timer`来设置周期性的任务。此方法适用于不需要UI交互的服务应用。 ```csharp using System.ServiceProcess; using System.Threading; public class MyWindowsService : ServiceBase { private Timer _timer; public MyWindowsService() { this.ServiceName = "My Windows Service"; } protected override void OnStart(string[] args) { // 初始化计时器,在启动后立即触发第一次回调,之后每隔10秒执行一次DoWork方法 _timer = new Timer(DoWork, null, 0, 10000); } private void DoWork(object state) { // 这里放置要定期执行的任务逻辑 } protected override void OnStop() { // 停止并释放资源 _timer?.Dispose(); } } ``` [^1] 该示例展示了如何通过构造函数初始化服务名称,并重写`OnStart()`与`OnStop()`两个虚方法来控制服务生命周期内的行为。其中,`_timer`被定义为私有字段用于存储定时器实例;当服务启动(`OnStart`)时创建新的`Timer`对象,指定回调函数以及间隔时间(单位毫秒),而在停止服务(`OnStop`)之前会先销毁定时器以防止内存泄漏或其他异常情况发生。 关于其他类型的定时器: - `System.Windows.Forms.Timer`: 主要用作窗体应用程序中的组件,其事件处理器总是在GUI线程上调用,因此不适合于无界面的服务程序[^4]。 - `System.Timers.Timer`: 能够跨多个线程工作,但是它可能会在同一时刻多次触发Elapsed事件如果前一个事件尚未完成,则可能导致并发问题。相比之下,`System.Threading.Timer`更加适合长时间运行且需要精确调度的任务[^2]. 为了确保最佳实践和服务稳定性建议采用`System.Threading.Timer`.
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值