写一个windows 的后台服务,后台服务需要每隔一段时间定期轮询数据库。
刚开始计划在Service 的OnStart事件中,起一个新的后台线程,由这个后台线程进行数据库轮询。后来发现用Timer 定期触发更好!
代码例子如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Timers;
namespace EDS.SMAP.WinService
{
/// <summary>
/// 服务地图后台服务,实现2个功能
/// </summary>
public partial class Service1 : ServiceBase
{
private System.Timers.Timer timer1;
public Service1()
{
InitializeComponent();
this.timer1 = new System.Timers.Timer();
this.timer1.Interval = 3600000;
this.timer1.Elapsed +=new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);
this.timer1.Enabled = false;
}
protected override void OnStart(string[] args)
{
// TODO: Add code here to start your service.
this.timer1.Enabled = true;
}
protected override void OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop your service.
this.timer1.Enabled = false;
}
/// <summary>
/// 定时器定期触发工作
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void timer1_Elapsed(object sender,System.Timers.ElapsedEventArgs e)
{
}
}
}
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Timers;
namespace EDS.SMAP.WinService
{
/// <summary>
/// 服务地图后台服务,实现2个功能
/// </summary>
public partial class Service1 : ServiceBase
{
private System.Timers.Timer timer1;
public Service1()
{
InitializeComponent();
this.timer1 = new System.Timers.Timer();
this.timer1.Interval = 3600000;
this.timer1.Elapsed +=new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);
this.timer1.Enabled = false;
}
protected override void OnStart(string[] args)
{
// TODO: Add code here to start your service.
this.timer1.Enabled = true;
}
protected override void OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop your service.
this.timer1.Enabled = false;
}
/// <summary>
/// 定时器定期触发工作
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void timer1_Elapsed(object sender,System.Timers.ElapsedEventArgs e)
{
}
}
}