Vista Schedule Task From Setup

放肆的年华 提交于 2019-11-30 10:00:44

Scheduled task is your way to go. Take a look at this page for how to setup the task with a script.

This took some putting together for me, so here's complete documentation for scheduling a task from a setup project.

Once you have your deployment project created, you're going to need to use Custom Actions to schedule the task. Walkthrough: Creating a Custom Action

Note: The walkthrough asks you to add the primary output to the Install node, even if you don't plan on doing anything custom during the Install step. This is important, so don't ignore it like I did. The Installer Class does some state management during this step, and needs to run.

The next step is to pass the installation directory to the custom action. This is done via the CustomActionData property. I entered /DIR="[TARGETDIR]\" for the commit node (I schedule my task during the commit step). MSDN: CustomActionData Property

Finally, you'll need to either access the task scheduling API, or use Process.Start to call schtasks.exe. The API will give you a more seamless and robust experience, but I went with the schtasks route because I had the command line handy.

Here is the code I ultimately ended up with. I registered it as a custom action for install, commit, and uninstall.

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();
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!