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

标签 c# scheduled-tasks

我正在使用此处的任务计划程序库: 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

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

谢谢, 周杰伦

最佳答案

我相信下面一行是罪魁祸首。

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();
    }

上面的任务在 Task Scheduler UI 中是这样的:

enter image description here

关于c# - 使用任务计划程序创建重复性任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21939133/

相关文章:

java - 如何让任务x在计划任务y之后运行

java - 使用默认值参数化 Spring @Scheduled

c# - 如何在 ASP.NET Core 3 上同时使用 Azure AD 身份验证和身份?

c# - 以编程方式断开和重新连接显示

windows - 在任务计划程序下将 mstsc.exe 作为批处理作业运行

javascript - sailsjs 中的公牛任务不起作用?

mysql - 仅将唯一条目从一个表复制到另一个 MySQL

c# - 具有空模型的局部 View

c# - c# 方法中的错误表示并非所有代码路径都返回一个值

c# - 白色 Blob 检测