我有一个windows服务,在其中我想每10秒创建一个文件。
我得到了很多评论,认为Windows服务中的计时器将是最好的选择。
我如何才能做到这一点?
发布于 2011-03-31 15:27:40
我不推荐使用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);
}
}
发布于 2013-01-08 12:00:44
这就是你要做的简单的事情
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using System.IO;
namespace MyService
{
public partial class Service1 : ServiceBase
{
Timer myTimer;
int x = 0;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
myTimer = new Timer(10000); // Sets a 10 second interval
myTimer.Elapsed +=new ElapsedEventHandler(myTimer_Elapsed);// Specifies The Event Handler
myTimer.Enabled = true; // Enables the control
myTimer.AutoReset = true; // makes it repeat
myTimer.Start(); // Starts the interval
}
protected void myTimer_Elapsed(object sender, ElapsedEventArgs e)
{
// All the Cool code that you need to run eg. Making a new file every 10 seconds
x++;
StreamWriter myFile = new StreamWriter("MyFile" + x.ToString() + ".txt");
myFile.Write("Something");
myFile.Close();
}
protected override void OnStop()
{
}
}
}
上面的代码是计时器的整个服务。我知道这是一个古老的帖子,但我花了几个小时才弄明白。希望它能帮助到外面的人。
发布于 2011-03-31 14:03:29
下面是如何使用Timer in Windows Service的示例。
https://stackoverflow.com/questions/5495842
复制相似问题