如何通过c#调度自定义任务

本文关键字:自定义 任务 调度 何通过 | 更新日期: 2023-09-27 18:09:03

我在c#应用程序中使用任务调度程序来调度任务。我想我对这个图书馆有了基本的了解。

但是现在我困在一个地方,我想创建一个自定义的动作,将执行在设定的时间表。像内置的动作,即EmailAction(这将发送邮件在设定的时间表),ShowMessageAction(这将显示警报消息在设定的时间表),我想创建一个动作,这将运行我的c#代码,代码将保存一些数据到我的数据库。

我尝试的是:我创建了一个类CustomAction继承了Action,像:

public class NewAction : Microsoft.Win32.TaskScheduler.Action
{
    public override string Id
    {
        get
        {
            return base.Id;
        }
        set
        {
            base.Id = value;
        }
    }
    public NewAction()
    {
    }
}
下面是我的任务调度程序代码:
    ..  
    ... 
    // 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";
        // Create a trigger that will fire the task at this time every other day
        TimeTrigger tt = new TimeTrigger();
        tt.StartBoundary = DateTime.Today + TimeSpan.FromHours(19) + TimeSpan.FromMinutes(1);
        tt.EndBoundary = DateTime.Today + TimeSpan.FromHours(19) + TimeSpan.FromMinutes(3);
        tt.Repetition.Interval = TimeSpan.FromMinutes(1);
        td.Triggers.Add(tt);
        // Create an action that will launch Notepad whenever the trigger fires
        td.Actions.Add(new NewAction());   <==========================
        // Register the task in the root folder
        ts.RootFolder.RegisterTaskDefinition(@"Test", td);
        // Remove the task we just created
        //ts.RootFolder.DeleteTask("Test");
    }
    ...
    ....

在行(箭头指向)上,我得到了异常:

值不在预期范围内任务调度程序

我不确定我想要达到的是可能的还是不可能的,如果可能的话,请引导我正确的方向?

如何通过c#调度自定义任务

根据我对你问题的理解。我已经实现了同样的事情,但我使用的是"Quartz"调度器而不是"Task Scheduler"。它很容易实现。也许你也可以试试这个

引用:http://quartznet.sourceforge.net/tutorial/

如果我说错了请纠正我