使用任务计划程序创建重复性任务

时间:2014-02-21 15:58:08

标签: c# scheduled-tasks

我在这里使用Task Scheduler库: taskscheduler.codeplex.com

根据他们的示例,我尝试使用以下行为创建任务: 任务应该在所有12个月中每1小时运行一次,包括该月的所有日子。

以下代码执行此操作,但任务不会每1小时重复一次。它运行一次然后在第二天运行。

                TaskDefinition td = ts.NewTask();
                td.RegistrationInfo.Description = "sample task";

                // Create a trigger that will execute very 1 hour. 
                var trigger = new MonthlyTrigger();
                trigger.StartBoundary = DateTime.Now + TimeSpan.FromSeconds(60);
                trigger.Repetition.Interval = TimeSpan.FromHours(1);
                trigger.Repetition.Duration = TimeSpan.FromHours(24);
List<int> days = new List<int>();
                for (int i = 1; i < 32; i++)
                {
                    days.Add(i);
                }
                trigger.DaysOfMonth = days.ToArray();

                td.Triggers.Add(trigger);
                td.Actions.Add(new ExecAction(Assembly.GetEntryAssembly().Location));
                // Register the task in the root folder
                ts.RootFolder.RegisterTaskDefinition(@"RemoteClient Task", td);

我也试过TimeTrigger,但这也不重复任务。如果我在“计划任务”窗口中看到创建的任务,我会看到以下内容:

Task Scheduler actions

如果您看到红色突出显示的部分,则任务重复已关闭。我需要启用它,以便我的任务可以每天每小时执行一次。在这个方向上任何帮助都会很棒。

谢谢, 杰

1 个答案:

答案 0 :(得分:4)

我相信以下行是罪魁祸首。

trigger.Repetition.Duration = TimeSpan.FromHours(24);

您想删除此行。我编写了以下程序,它按预期工作。

static void Main(string[] args)
    {
        // Get the service on the local machine
        using (TaskService ts = new TaskService())
        {
            // Create a new task definition and assign properties
            TaskDefinition td = ts.NewTask();
            td.RegistrationInfo.Description = "Does something";

            // Add a trigger that, starting now, will fire every day
            // and repeat every 1 minute.
            var dt = new DailyTrigger();
            dt.StartBoundary = DateTime.Now;
            dt.Repetition.Interval = TimeSpan.FromSeconds(60);
            td.Triggers.Add(dt);

            // Create an action that will launch Notepad whenever the trigger fires
            td.Actions.Add(new ExecAction("notepad.exe", "c:\\test.log", null));

            // Register the task in the root folder
            ts.RootFolder.RegisterTaskDefinition("Test", td);
        }
        Console.ReadLine();
    }

以上任务在任务计划程序UI中的显示方式:

enter image description here

相关问题