入门例子
using log4net;using System;using System.Timers;using Topshelf;namespace ConsoleAppTest{ class Program { static void Main(string[] args) { log4net.Config.XmlConfigurator.Configure(); HostFactory.Run(x => { x.Service(); x.RunAsLocalSystem(); // 服务使用NETWORK_SERVICE内置帐户运行。身份标识,有好几种方式,如: //x.RunAs("username", "password"); x.RunAsPrompt(); x.RunAsNetworkService(); x.SetServiceName("ConsoleAppTest服务名称"); x.SetDisplayName("ConsoleAppTest显示名称"); x.SetDescription("ConsoleAppTest服务描述"); }); } } public class TownCrier : ServiceControl { readonly Timer _timer; readonly ILog _log = log4net.LogManager.GetLogger("wolflogInfo"); public TownCrier() { //10秒运行一次 _timer = new Timer(10000) { AutoReset = true }; _timer.Elapsed += (sender, eventArgs) => _log.Info(DateTime.Now); } bool ServiceControl.Start(HostControl hostControl) { _log.Info("ConsoleAppTest is Started"); _timer.Start(); return true; } bool ServiceControl.Stop(HostControl hostControl) { _log.Info("ConsoleAppTest is Stop"); _timer.Start(); return true; } }}
Log4的config配置
安装运行命令
安装:ConsoleAppTest install
卸载:ConsoleAppTest uninstall启动:ConsoleAppTest start停止:ConsoleAppTest stop需要用管理员运行程序
多实例安装
ConsoleAppTest –instance "ConsoleAppTest2" install
ConsoleAppTest –instance "ConsoleAppTest2" uninstall也可以 sc delete 删除