【发布时间】:2010-12-18 23:41:44
【问题描述】:
我正在使用 Visual Studio 2008 中的安装向导项目部署 C# 应用程序。
让 Windows 安排我的应用程序定期运行(例如每 8 小时)的最简单方法是什么?我更喜欢在应用程序安装期间进行这种安排,以简化最终用户的设置。
谢谢!
【问题讨论】:
标签: c# visual-studio deployment scheduled-tasks setup-deployment
我正在使用 Visual Studio 2008 中的安装向导项目部署 C# 应用程序。
让 Windows 安排我的应用程序定期运行(例如每 8 小时)的最简单方法是什么?我更喜欢在应用程序安装期间进行这种安排,以简化最终用户的设置。
谢谢!
【问题讨论】:
标签: c# visual-studio deployment scheduled-tasks setup-deployment
这花了我一些时间,所以这里有完整的文档,用于从设置项目中安排任务。
创建部署项目后,您需要使用Custom Actions 来安排任务。 Walkthrough: Creating a Custom Action
注意:演练要求您将主要输出添加到安装节点,即使您不打算在安装步骤期间执行任何自定义操作。 这很重要,所以不要像我一样忽略它。 Installer 类在这一步进行一些状态管理,需要运行。
下一步是将安装目录传递给自定义操作。这是通过CustomActionData property 完成的。我为提交节点输入了/DIR="[TARGETDIR]\"(我在提交步骤中安排了我的任务)。 MSDN: CustomActionData Property
最后,您需要访问任务调度 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();
}
}
}
【讨论】:
计划任务是您的最佳选择。查看此页面,了解如何使用 script 设置任务。
【讨论】: