简体   繁体   中英

How to schedule custom task through c#

I am using Task Scheduler for scheduling my task in c# application. I think i got the basic understanding of this library.

But now i stuck in a place where i want to create a custom action which will execute on the set schedule.Like the built-in action ie EmailAction ( Which will send mail on set schedule ), ShowMessageAction ( Which will show alert message on set schedule ), i want to create an action which will run my c# code and that code will save some data to my database.

What I tried yet is: I created a class CustomAction which inherits Action , like :

public class NewAction : Microsoft.Win32.TaskScheduler.Action
{
    public override string Id
    {
        get
        {
            return base.Id;
        }
        set
        {
            base.Id = value;
        }
    }

    public NewAction()
    {
    }
}

And here is my task scheduler code :

    ..  
    ... 
    // 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");
    }
    ...
    ....

On the line (pointed by arrow) i am getting the exception :

value does not fall within the expected range task scheduler

I am not sure what i am trying to achieve is even possible or not, if it is possible than please guid me on the correct direction?

According my understanding of your question. I had implemented same thing, but I had used "Quartz" Scheduler instead of "Task Scheduler". It is very easy to implement. May be you can also try with this.

To reference: http://quartznet.sourceforge.net/tutorial/

Please correct me if I am wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM