第一步,Vs的NuGet下载安装Topshelf。
第二步,
static void Main(string[] args)
{
HostFactory.Run(x =>
{
x.UseLog4Net();
x.Service<TownCrier>(s =>
{
s.ConstructUsing(name => new TownCrier());
s.WhenStarted(tc => tc.Start());
s.WhenStopped(tc => tc.Stop());
});
x.SetDescription("服务的描述");
x.SetDisplayName("显示的名称");
x.SetServiceName("服务名称");
x.EnablePauseAndContinue();
});
}
public class TownCrier
{
readonly Timer _timer;
public TownCrier()
{
_timer = new Timer(60000) { AutoReset = true };
_timer.Elapsed += new ElapsedEventHandler(OnTick);
_timer.Elapsed += (sender, eventArgs) => Console.WriteLine("It is {0} and all is well", DateTime.Now);
}
protected virtual void OnTick(object sender, ElapsedEventArgs e)
{
RequestHelper.Start();
}
public void Start() { _timer.Start(); }
public void Stop() { _timer.Stop(); }
}
第三步,将需要执行的任务放到其中,调整时间操作。