Par*_*att 19 .net service windows-services timer
我有一个Windows服务,我想在每10秒钟创建一个文件.
我得到了很多评论,Windows服务中的Timer将是最好的选择.
我怎样才能做到这一点?
Jon*_*eet 31
首先,选择合适的计时器.您想要System.Timers.Timer或者System.Threading.Timer- 不要使用与UI框架相关联的(例如System.Windows.Forms.Timer或DispatcherTimer).
定时器通常很简单
Elapsed事件添加处理程序(或在构造时传递回调),一切都会好的.
样品:
// 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...");
}
}
Run Code Online (Sandbox Code Playgroud)
我在这个页面上有更多的信息,虽然我很长时间没有更新.
jga*_*fin 12
我不建议,System.Timers.Timer因为它默默地吃掉未处理的异常,因此隐藏了你应该修复的错误.如果你没有正确处理异常,那么你的代码就会爆炸.
至于System.Threading.Timer我倾向于使用该Change方法以这样的模式启动/停止计时器:
public class MyCoolService
{
Timer _timer;
public MyCoolService()
{
_timer = new Timer(MyWorkerMethod, Timeout.Infinite, Timeout.Infinite);
}
protected void OnStart()
{
_timer.Change(15000, Timeout.Infinte);
}
protected void MyWorkerMethod()
{
//pause timer during processing so it
// wont be run twice if the processing takes longer
// than the interval for some reason
_timer.Change(Timeout.Infinite, Timeout.Infinite);
try
{
DoSomeWork();
}
catch (Exception err)
{
// report the error to your manager if you dare
}
// launch again in 15 seconds
_timer.Change(15000, Timeout.Infinite);
}
}
Run Code Online (Sandbox Code Playgroud)