Programming implementation planning task

xiaoxiao2021-03-05  25

When some tasks that need to be performed timed, such as: Timed backup database, timing acquisition network data, etc., you need to plan tasks. Window also has a planned task but there are many shortcomings that must be manually configured, and it is also very troublesome to deploy, and the accuracy of time is one minute, and the application configuration tasks can only be configured. The task program implemented here is that it can be programmed, which can be flexible, and the accuracy of time is one second, and is not achieved by polling time. The efficiency is relatively high. You can write a service in the Windows service, use it to manage all planned task logic.

The library source code is as follows: / ************************************************** *********************************************************** (C) 2003-2005 C2217 Studio * All rights reserved * * File Name: Task.cs * File ID: * Programming Language: C # * File Description: Implement the scheduled task's scheduling mechanism. You can implement a variety of task scheduling mechanisms (define time accurate to second): * 1. Immediately (once) * 2. Program execution (once, define task begins to execute the date) * 3. Immediately (loop execution, multiple times ) * 4. Program implementation (loop executes repeatedly, define the date to start the task execution) * Interface can be achieved by developing their own implementation plans ISchedule * * current version: 1.0 * alternate versions: * * author: Deng Yang are * Email: DYJ057@gmail.com 0 Create Date: 2005-4-8 * Last modified Date: 2005-4-8 * * History Modification Record:

*********************************************************** ************************************************* / Using System; use system.collections Using system.threading; // using nunit.framework;

Namespace IBMS.UTILITY.TASK {

#REGION Task Plan Interface and Some Standard Implement ///

/// Plan /// public interface ischedule {/// /// Return to the original plan execution time /// < / summary> datetime executionTime {get; set;} /// /// initialization execution time in the current time scale error /// long duetime {GET;}

///

/// cycle cycle /// long period {get;}

}

///

/// Plan to perform task /// public class immediateExecution: ischadule {#Region ischedule member

Public DateTime ExecutionTime {Get {// Todo: Add immediatelyshedule.executionTime getter Implement Return DateTime.now;} set {;}}

Public long duetime {get {return 0;}}

PUBLIC Long Period {Get {// Todo: Add ImmediatelyShedule.Period getter Implement Return Timeout.Infinite;}} #ENDREGONTE

///

/// Plan an operation once in a certain future, if this time is smaller than the current time, it becomes an immediate execution /// public class scheduleExecutiononce: ischadule {

///

/// Constructor /// /// Scheduled time public scheduleexecutiononce (datetime schedule) {m_schedule = schedule;}

Private datetime m_schedule;

#Region ischedule member

Public DateTime ExecutionTime {get {// Todo: Add ScheduleExecutionOcut.executionTime GetTer Implement Return M_SCHEDULE;} set {m_schedule = value;}}

///

/// How long does it take to run /// public longuetime {get {long ms = (m_schedule.ticks- datetime.now.ticks) / 10000;

IF (ms <0) ms = 0; Return MS;}}

PUBLIC Long Period {Get {// Todo: Add ScheduleExecutiononce.Period getter Implement Return Timeout.Infinite;}}

#ndregion}

///

/// periodic execution plan /// public class cycExecution: ischedule {//// /// Constructor, starting in a future time /// /// Scheduled time /// cycle time public cycexecution (DateTime Shedule, Timespan Period) {m_schedule = SHEDULE; M_PERIOD = period;

///

/// Constructor, start running /// /// cycle time public cycExecution (timespan period) {m_schedule = datetime. NOW; m_period = period;}

Private datetime m_schedule; private timeespan m_period; #Region ischedule member

Public long duetime {get {long ms = (m_schedule.ticks- datetime.now.ticks) / 10000;

IF (ms <0) ms = 0; Return MS;}}

Public DateTime ExecutionTime {Get {// Todo: Add Cycexecution.executionTime GetTer Implement Return M_SCHEDULE;} set {m_schedule = value;}

} PUBLIC Long Period {Get {// Todo: Add Cycexecution.Period GetTer Realization Return M_Period.Ticks / 10000;}}

#ndregion

}

#ndregion

#REGION Task Implementation ///

/// Plan Task Basin /// The start-up task is completed in the working work thread, and will return immediately after calling the boot method. /// // Usage: /// (1) If you want to create your own task, you need to inherit a new class from this class and then overload the Execute (Object Param) method. // / Implement your own task, then add the task to the Task Management Center to start and stop. ///, for example: /// taskcenter center = new taskcenter (); /// Task newtask = new task (new immediateexecution ()); /// center.addtask (newtask); /// center.startAllTask ​​();

/// (2) Write his own task to the TimerCallback commission, then generate an instance of a Task class, // / / set its Job and JobParam properties, and then Start can start the service. It is no longer possible to use the task management center. ///, for example: /// Task newtask = new task (new immediateexecution ()); /// newtask.job = new timercallback (newtask.execute); /// newtask.jobparam = "test immedialte task"; // Add your own parameters /// newtask.start (); /// /// public class task {///

/// Structure function /// /// Develop an execution plan public task for each task public task (ISCHEDULE SCHEDULE) {IF (New Argumentnullexception ("Schedule");}

m_schedule = schedule;}

///

/// Start task /// public void start () {// Start timer m_timer = new time (m_exectsk, m_param, m_schedule.duetime, m_schedule.period);} // / /// Stop Task /// public void stop () {// Stop timer m_timer.change (timeout.infinite, timeout.infinite);

///

/// task content /// /// task function parameter public virtual void execute (object param) {// you need to be heavy Load the function, but you need to call Base.execute (); m_lasteexecutetime = datetime.now in your new function.

if (m_schedule.Period == Timeout.Infinite) {m_nextExecuteTime = DateTime.MaxValue; // next run time does not exist} else {TimeSpan period = new TimeSpan (m_schedule.Period * 1000); m_nextExecuteTime = m_lastExecuteTime period;} }

///

/// Task execution time /// public datetime nextexecutetime {get {return m_nextexecutetime;}}

DateTime m_nextexecutetime; ///

/// Execute the plan /// public ischedule shedule {get {return m_schedule;}}

PRIVATE ISCHEDULE M_SCHEDULE;

///

/// System Timer /// private timer m_timer; /// /// Task content /// public timerCallback job {get {return m_exectask; } Set {m_exectask = value;}}

Private timerCallback m_exectask;

///

/// Task parameter /// public object jobparam {set {m_param = value;}} private object m_param;

///

/// task name /// public string name {get {return m_name;} set {m_name = value;}} private string m_name; /// /// task Description /// public string description {get {return {m_description;} set {m_description = value;}} private string m_description; /// /// This task last execution time /// < / summary> public datetime lastexecutetime {get {return m_lastexecutetime;}} private datetime m_lastexecutetime

}

#ndregion

#REGON boot task ///

/// Task Management Center /// Use it to manage one or more simultaneous running tasks /// public class taskcenter {/// / // Constructor /// public taskcenter () {m_scheduletasks = new arraylist ();}

///

/// Add Task /// New Task public void addtask (task newtask) {m_scheduletasks.add (newtask); }

///

/// Delete task /// /// The task that will be deleted, you may need to stop the task public void deltask Deltask {m_scheduletasks.remove (deltask);

///

/// Start all tasks /// public void startAlltask () {Foreach (Task Task In scheduletasks) {starttask;}

///

/// Start a task /// /// public void starttask (task task) {// standard startup method IF (Task .Job == null) {task.job = new timerCallback (task.execute);

Task.start ();

///

/// Terminate all tasks /// public void terminateAllTask ​​() {moreach (task task in scheduletasks) {TERMINATETASK (TASK);}} /// /////// Termination of a task /// public void terminatetask (task task) {task.stop ();} /// /// All tasks /// arraylist scheduletasks {get {return m_scheduletasks;}} private arraylist m_scheduletasks;

///

/// unit test code /// public void testtaskcenter () {taskcenter center = new taskcenter ();

// Test Immedialte Task Task NEWTASK = New Task (New ImmediateExecution ()); NewTask.Job = New TimerCallback (NewTask.execute); NewTask.jobParam = "Test Immedialte Task";

// Test Excute Once Task DateTime Sheduletime = DateTime.now.addSeconds (10); ScheduleExecutiononce Future = New ScheduleExecutiononCE (Sheduletime);

Task sheduletask = new task; sheduletask.job = new timerCallback (Sheduletask.execute); Sheduletask.jobParam = "Test Excute Once Task"; // Test Cyc Task At Once

Cycexecution CYC = New Cycexecution (New Timespan (0,0,2)); task cystask = new task; cystask.job = new timerCallback (cystask.execute); cystask.jobparam = "Test Cyc Task";

// Test Cys Task At Schedule

Cycexecution cycshedule = new cycExecution (DateTime.now.addseconds (8), New Timespan (0,0,2));

Task cycsheduletask = new task; cycsheduletask.job = new timercallback (cysticuletask.jobparam = "test cyc shedule task);

Center.addtask; center.addtask; center.addtask; center.addtask;

Center.startAlltask ();

Console.readline ();

Console.writeline (NewTask.lasteexecuteTime);}}

#ndregion}

Test code: using system.threading;

Namespace ibms.utility.task.test {///

/// Interpret how to create its own task class, and use them /// class testtask: ibms.utility.task.task {public testtask ISCHEDULE SCHEDULE: BASE (SCHEDULE) {}

Public override void execute (object param) {// must keep Base.execute (param);

Console.writeline ("Begin to Execute A Long Job ... nextExecutetime: {0}", this.nextexecutetime);

Thread.Sleep (5000); console.writeline ("Test Tast Execute Job.last ExecuteTime {0},", this.lastexecutetime);

}

///

/// The primary entry point of the application. /// [stathread] static void main (string [] args) {// // Todo: Add code here to start the application // taskcenter center = new taskCenter ();

// Test Immedialte Task Task NEWTASK = New Testtask (New ImmediateExecution ()); NewTask.jobParam = "Test Immedialte Task";

// Test excute once task DateTime sheduleTime = DateTime.Now.AddSeconds (10); ScheduleExecutionOnce future = new ScheduleExecutionOnce (sheduleTime); Task sheduleTask = new TestTask (future); sheduleTask.JobParam = "Test excute once task"; // Test Cyc Task At Cycexecution CYC = New Cycexecution (New Timespan (0,0,2)); Task Cystask = New Testtask (CYC); cystask.jobparam = "Test Cyc Task";

// Test cys task at schedule CycExecution cycShedule = new CycExecution (DateTime.Now.AddSeconds (8), new TimeSpan (0,0,2)); Task cycSheduleTask = new TestTask (cycShedule); cycSheduleTask.JobParam = "Test cyc Shedule Task; center.addtask; center.addtask; center.addtask; center.addtask;

Center.startAlltask ();

Console.readline (); console.writeline ("Terminate All Task");

Center.TerminateAllTask ​​(); console.readline ();

}

}

转载请注明原文地址:https://www.9cbs.com/read-37326.html

New Post(0)