安装程序中的Vista计划任务

时间:2009-11-21 06:53:45

标签: c# visual-studio deployment scheduled-tasks setup-deployment

我正在使用Visual Studio 2008中的安装向导项目部署C#应用程序。

让Windows安排我的应用程序定期运行(例如每8小时)的最简单方法是什么?我更喜欢在应用程序安装期间进行此调度以简化最终用户的设置。

谢谢!

2 个答案:

答案 0 :(得分:10)

这对我来说需要一些整理,所以这里是完整的文档,用于从安装项目安排任务。

创建部署项目后,您将需要使用Custom Actions来安排任务。 Walkthrough: Creating a Custom Action

注意:演练要求您将主要输出添加到“安装”节点,即使您不打算在“安装”步骤中执行任何自定义操作也是如此。 这很重要,所以不要像我那样忽略它。安装程序类在此步骤中执行一些状态管理,并且需要运行。

下一步是将安装目录传递给自定义操作。这是通过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();
        }
    }
}

答案 1 :(得分:0)

计划任务是您的最佳选择。请查看此页面,了解如何使用script设置任务。

相关问题