您的位置:首页 > 其它

windows服务应用--做个简单的定时调用EXE功能(笔记)

2011-05-20 15:12 267 查看
先给一个LINK~~别人写的创建服务的步骤

好,这里感谢一下本园的“技术无极限”这们人兄;

copy他的: (红色为我加的)

. 新建一个项目

2. 从一个可用的项目模板列表当中选择Windows服务

3. 设计器会以设计模式打开

4. 从工具箱的组件表当中拖动一个Timer对象到这个设计表面上 (注意: 要确保是从组件列表而不是从Windows窗体列表当中使用Timer) ,即它所属的命名空间是:System.Timers.Timer

5. 设置Timer属性,Interval属性1000毫秒;(每秒触发一次timer的Elapsed事件)
6. 然后为这个服务填加功能

7.双击这个Timer,然后在里面写一些代码,比如(下面我以调用一个生成XML文件的EXE为例)

private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)

{

DateTime dt = DateTime.Now;

int hour = 3, minute = 0, second = 0;

if (ConfigurationManager.AppSettings["RunTime"] != null)

{

string[] setTime = ConfigurationManager.AppSettings["RunTime"].Split(':');

if (setTime.Length == 3)

{

int.TryParse(setTime[0], out hour);

int.TryParse(setTime[1], out minute);

int.TryParse(setTime[2], out second);

}

}

if (dt.Hour == hour && dt.Minute == minute && dt.Second == second)

{

string sitemapExePath = ConfigurationManager.AppSettings["SiteMapExePath"];

if (sitemapExePath != null && Directory.Exists(sitemapExePath))

{

try

{

Process proc = new Process();

proc.StartInfo.WorkingDirectory = sitemapExePath;

proc.StartInfo.UseShellExecute = true; //use false if you want to hide the window

proc.StartInfo.FileName = "ConsoleSiteMap";

proc.Start();

proc.WaitForExit();

proc.Close();

WriteLog("生成成功");

}

catch (Exception ex)

{

WriteLog("Error:" + ex.Message);

}

}

}

}

(执行时间是通过配置文件读的)

8. 将这个服务程序切换到设计视图

9. 右击设计视图选择“添加安装程序”

10. 切换到刚被添加的ProjectInstaller的设计视图

11. 设置serviceInstaller1组件的属性:

1) ServiceName = My Sample Service

2) StartType = Automatic (开机自动运行)

12. 设置serviceProcessInstaller1组件的属性 Account = LocalSystem

下面步骤则是安装服务;你可以WIN+R,输入cmd调出命令 框,

cd 到WINDOWS文件夹Microsoft.NET\Framework\v4.0.30319,(看你装的framework是多少了;)

13. 改变路径到你项目所在的bin\Debug文件夹位置(如果你以Release模式编译则在bin\Release文件夹)
14. 执行命令“InstallUtil e:\MyWindowsService.exe”注册这个服务,使它建立一个合适的注册项。(InstallUtil这个程序在WINDOWS文件夹\Microsoft.NET\Framework\4.0.30319下面)

e:\MyWindowsService.exe这个为刚才那个服务程序的路径,这里只是举个例子;

15. 右击桌面上“我的电脑”,选择“管理”就可以打计算机管理控制台,(或者win+R --> services.msc)

16. 在“服务和应用程序”里面的“服务”部分里,你可以发现你的Windows服务已经包含在服务列表当中了
17. 右击你的服务选择启动就可以启动你的服务了

那就会在你设定的时间执行相关的功能了(这里是调用EXE生成XML文件),另。。改过配置文件的话要restart服务才有效的;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐