来自 .NET 的 Windows 上的任务计划程序问题

Issues with Task Scheduler on Windows from .NET

我正在使用 Task Scheduler Managed Wrapper from https://taskscheduler.codeplex.com/ 在 windows 7 上构建一个针对 .NET 4 的应用程序,它在删除它自己创建的任何旧任务后创建了多个任务。

任务注册似乎成功,但任务没有启动并且以某种方式损坏了 Task Scheduler,如下所示:

图中的错误对话框弹出六次,这是我的应用程序删除然后重新创建的任务数。当 Task Scheduler MMC Console 首次启动时以及选择 House of Synergy 文件夹时都会发生这种情况。

代码有点冗长,但很有必要,可以编译了:

namespace TaskSchedulerHelper
{
    using System;
    using System.Diagnostics;
    using System.Linq;
    using System.Security.Principal;
    using System.Windows.Forms;
    using Microsoft.Win32.TaskScheduler;

    internal static class Program
    {
        [STAThread]
        private static void Main (string [] args)
        {
            var now = DateTime.Now;
            var folderName = @"House of Synergy";
            var taskNamePrefix = @"ShutDown Power Outage";
            var applicationName = @"Task Scheduler Helper";

            var times = new TimeSpan []
            {
                TimeSpan.FromHours(02), // 02:00 AM
                TimeSpan.FromHours(06), // 06:00 AM
                TimeSpan.FromHours(11), // 11:00 AM
                TimeSpan.FromHours(15), // 03:00 PM
                TimeSpan.FromHours(19), // 07:00 PM
                TimeSpan.FromHours(23), // 11:00 PM
            };

            try
            {
                Console.Title = applicationName;

                Console.WriteLine(applicationName);
                Console.WriteLine();

                // Uses the Task Scheduler Managed Wrapper
                //  from https://taskscheduler.codeplex.com/.
                //  Release: 2.3.0. Status: Stable.
                //  Date: Thu Dec 18, 2014 at 12:00 PM.
                using (TaskService service = new TaskService())
                {
                    var folder = service
                        .RootFolder
                        .SubFolders
                        .FirstOrDefault(f => (string.Compare(f.Name, folderName, StringComparison.InvariantCultureIgnoreCase) == 0));

                    if (folder == null) { folder = service.RootFolder.CreateFolder(folderName); }

                    var tasks = folder
                        .Tasks
                        //.Where(t => t.Name.StartsWith(taskNamePrefix, StringComparison.InvariantCultureIgnoreCase))
                        .ToList();

                    if (tasks.Any())
                    {
                        // Delete existing tasks.
                        Console.WriteLine("Deleting existing tasks.");
                        foreach (var task in tasks)
                        {
                            Console.Write(" - Deleting Task: {0}: ", task.Name);

                            try
                            {
                                task.Stop();

                                //task.Enabled = false; // Throws ComException: Element not found. (Exception from HRESULT: 0x80070490).
                                //Console.WriteLine(task.State); // Throws ComException: Element not found. (Exception from HRESULT: 0x80070490).

                                task.RegisterChanges();
                                folder.DeleteTask(task.Name, false);
                                task.Dispose();

                                Console.WriteLine("Done.");
                            }
                            catch (Exception exception)
                            {
                                Console.WriteLine("Exception: {0}.", exception);
                            }
                        }
                    }

                    Console.WriteLine();
                    Console.WriteLine("Creating new Tasks.");

                    foreach (var time in times)
                    {
                        var dateTimeNow = now.Date;
                        var definition = service.NewTask();
                        var dateTimeTrigger = now.Date.Add(time);
                        var taskName = taskNamePrefix + " " + dateTimeTrigger.ToString(@"hh-mm tt");

                        Console.Write(" - Creating Task: {0}: ", taskName);

                        try
                        {
                            definition.RegistrationInfo.Author = WindowsIdentity.GetCurrent().Name;
                            definition.RegistrationInfo.Date = DateTime.Now;
                            definition.RegistrationInfo.Description = "ShutDown event due to power outage at [" + dateTimeTrigger.ToLongTimeString() + "].";
                            definition.RegistrationInfo.Source = applicationName;
                            definition.RegistrationInfo.Version = new Version(1, 0, 0, 0);

                            definition.Settings.AllowDemandStart = true;
                            definition.Settings.AllowHardTerminate = false;
                            definition.Settings.Compatibility = TaskCompatibility.V2_1; // Windows 7 and above.
                            definition.Settings.DisallowStartIfOnBatteries = false;
                            definition.Settings.DisallowStartOnRemoteAppSession = false;
                            definition.Settings.Enabled = true;
                            definition.Settings.Hidden = false;
                            definition.Settings.MultipleInstances = TaskInstancesPolicy.IgnoreNew;
                            definition.Settings.Priority = ProcessPriorityClass.High;
                            definition.Settings.RestartCount = 10;
                            definition.Settings.RestartInterval = TimeSpan.FromMinutes(1);
                            definition.Settings.RunOnlyIfIdle = false;
                            definition.Settings.RunOnlyIfNetworkAvailable = false;
                            definition.Settings.StartWhenAvailable = true;
                            definition.Settings.StopIfGoingOnBatteries = false;
                            definition.Settings.UseUnifiedSchedulingEngine = true;
                            definition.Settings.WakeToRun = false;

                            definition.Actions.Add(new ShowMessageAction("Message Body", "Message Title"));
                            definition.Triggers.Add(new DailyTrigger() { StartBoundary = dateTimeTrigger.Subtract(TimeSpan.FromMinutes(10)), });

                            var task = folder.RegisterTaskDefinition(taskName, definition);

                            task.Enabled = true;
                            task.RegisterChanges();
                            // Always succeeds.
                            Console.WriteLine("Done.");

                            try
                            {
                                Console.WriteLine("   - Task Validation: ", task.Definition.Validate(throwException : true) ? "Succeeded." : "Failed.");
                            }
                            catch (Exception exception)
                            {
                                // Validation always fails.
                                Console.WriteLine("   - Task Validation Exception: {0}.", exception);
                            }
                        }
                        catch (Exception exception)
                        {
                            Console.WriteLine("Exception: {0}.", exception.Message);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                Console.Write(exception);
            }

            Console.WriteLine();
            Console.WriteLine();
            Console.Write("Press any key to continue...");
            Console.ReadKey(true);
        }
    }
}

注释掉 task.RegisterChanges(); 和随后的两行似乎解决了这个问题。