Mar*_*rko 3 c# windows-services timer
我需要帮助.我有Windows服务,我需要在特定时间每小时运行一次这项服务,例如:09:05,10:05,11:05,....我的服务现在每小时开始,但从我开始这项服务的每个小时开始.那么我怎样才能实现我的需求呢.
我的代码:
public partial class Service1 : ServiceBase
{
System.Timers.Timer timer = new System.Timers.Timer();
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
this.WriteToFile("Starting Service {0}");
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
timer.Interval = 60000;
timer.Enabled = true;
}
protected override void OnStop()
{
timer.Enabled = false;
this.WriteToFile("Stopping Service {0}");
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
this.WriteToFile(" interval start {0}");
} }
Run Code Online (Sandbox Code Playgroud)
您应该从计时器每隔'n'秒(例如1)检查当前时间:
public partial class Service1 : ServiceBase
{
System.Timers.Timer timer = new System.Timers.Timer();
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
this.WriteToFile("Starting Service {0}");
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
timer.Interval = 1000; // 1000 ms => 1 second
timer.Enabled = true;
}
protected override void OnStop()
{
timer.Enabled = false;
this.WriteToFile("Stopping Service {0}");
}
private int lastHour = -1;
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
var curTime = DateTime.Now; // Get current time
if (lastHour != curTime.Hour && curTime.Minute == 5) // If now 5 min of any hour
{
lastHour = curTime.Hour;
// Some action
this.WriteToFile(" interval start {0}");
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4871 次 |
| 最近记录: |