windows 窗体应用程序是在用户登录后才运行的。特别是对于服务器这种多用户系统,尽管设置了开机自启动,但是在程序运行过程中,运行改程序的用户被注销了,程序就关掉了。除非有人重新登录或服务器重启。
如果想要程序一直运行在服务器上,最好是把程序写成windows服务程序。这样程序会随着系统的自动启动而启动,自动关闭而关闭,不需要用户直接登录,直接开机就可以启动。
注意windows服务程序是没有界面的,所以要定义日志文件保存运行过程中出现的问题。如果用到了定时器也要是系统的定时器。
下面示例如何建windows服务程序,以VS2013为例:
1. 建立windows服务
看看VS都生成了什么
2. 重命名Service1,这个名称是以后运行的windows服务的名称,这里改成SQLServerSyncService.cs
打开SQLServerSyncService.cs,添加后台代码
namespace SQLServerSyncService
{
public partial class SQLServerSyncService : ServiceBase
{
private System.Timers.Timer timer1;//系统定时器
public int No = 0;
public SQLServerSyncService()
{
InitializeComponent();
}
protected void timer1_Tick(object source, ElapsedEventArgs e)
{
timer1.Stop();
int timek = 0;
OperatorDatatable test = new OperatorDatatable();
if (test.sw != null)
{
test.sw.WriteLine("第" + (No + 1).ToString() + "次同步数据库错误信息:");
}
DateTime time1 = DateTime.Now;
try
{
if (test.ReadDataFromDatabase())
{
test.WriteDataToDatabase();
bool flag = false;
do
{
flag = test.DeleteSyncData();
Thread.Sleep(1000);
} while (!flag);
}
}
finally
{
test.DisposeAllResource();
test.CloseServer();
test.SaveLogFile();
DateTime time2 = DateTime.Now;
timek = (time2 - time1).Hours * 3600 + (time2 - time1).Minutes * 60 + (time2 - time1).Seconds;
}
No++;
timer1.Start();
}
protected override void OnStart(string[] args)
{
timer1 = new System.Timers.Timer();
timer1.Elapsed += new ElapsedEventHandler(timer1_Tick);
string timestr = XMLConfig.GetValue("appSettings", "add", "SyncInterval", "value");//同步时间间隔
timer1.Interval = (int)(float.Parse(timestr) * 60 * 1000);
timer1.AutoReset = true;//设置是执行一次(false)还是一直执行(true)
timer1.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件
}
protected override void OnContinue()
{//服务恢复时
timer1.Enabled = true;
}
protected override void OnStop()
{
timer1.Enabled = false;
}
}
}
3.添加安装程序,主要是为了设置windows服务程序,也可以自己写代码实现,但是何必呢。
右键
会出现两个组件
右键serviceInsraller1,选择属性,将ServiceName的值改为SQLServerSyncService。(此名称是以后服务的名称)
右键serviceProcessInsraller1,选择属性,将Account的值改为LocalSystem。
生成解决方案,最后把生成的exe程序拷贝到方便记的目录。次目录是后续安装生成的服务的路径。
4.安装该服务程序。 打开VS开发人员命令提示工具,注意要以管理员的身份运行,否则会报错:Windows服务安装异常:System.Security.SecurityException: 未找到源,但未能搜索某些或全部事件日志。不可 访问的日志: Security
输入命令InstallUtil.exe C:\Server\SQLServerSyncService.exe, 回车
5.服务程序安装好了,启动就好了
在上面的VS开发人员调试工具或者DOC下面输入services.msc,回车弹出服务对话框,找到我们的服务程序,启动就可以了