我正在使用 Visual Studio 2008 中的安装向导项目部署 C# 应用程序。
让 Windows 安排我的应用程序定期运行(例如每 8 小时)的最简单方法是什么?我更喜欢在应用程序安装期间进行此调度,以简化最终用户的设置。
Thanks!
这需要我进行一些整理,因此这里是从设置项目安排任务的完整文档。
创建部署项目后,您将需要使用自定义操作来安排任务。演练:创建自定义操作
Note:本演练要求您将主输出添加到安装节点,即使您不打算在安装步骤期间执行任何自定义操作。这很重要,所以不要像我一样忽视它。安装程序类在此步骤中进行一些状态管理,并且需要运行。
下一步是将安装目录传递给自定义操作。这是通过自定义操作数据属性。我进入了/DIR="[TARGETDIR]\"
对于提交节点(我在提交步骤期间安排我的任务)。MSDN:CustomActionData 属性
最后,您需要访问任务调度 API,或者使用Process.Start
打电话schtasks.exe。 API 将为您提供更加无缝和强大的体验,但我选择了 schtasks 路线,因为我有方便的命令行。
这是我最终得到的代码。我将其注册为安装、提交和卸载的自定义操作。
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.Security.Permissions;
using System.Diagnostics;
using System.IO;
namespace MyApp
{
[RunInstaller(true)]
public partial class ScheduleTask : System.Configuration.Install.Installer
{
public ScheduleTask()
{
InitializeComponent();
}
[SecurityPermission(SecurityAction.Demand)]
public override void Commit(IDictionary savedState)
{
base.Commit(savedState);
RemoveScheduledTask();
string installationPath = Context.Parameters["DIR"] ?? "";
//Without the replace, results in c:\path\\MyApp.exe
string executablePath = Path.Combine(installationPath, "MyApp.exe").Replace("\\\\", "\\");
Process scheduler = Process.Start("schtasks.exe",string.Format("/Create /RU SYSTEM /SC HOURLY /MO 2 /TN \"MyApp\" /TR \"\\\"{0}\\\"\" /st 00:00", executablePath));
scheduler.WaitForExit();
}
[SecurityPermission(SecurityAction.Demand)]
public override void Uninstall(IDictionary savedState)
{
base.Uninstall(savedState);
RemoveScheduledTask();
}
private void RemoveScheduledTask() {
Process scheduler = Process.Start("schtasks.exe", "/Delete /TN \"MyApp\" /F");
scheduler.WaitForExit();
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)