[Practice] developing windows Services with good scalability

Source: Internet
Author: User

During work, we often need to develop windows Services. Therefore, a windows program with good maintainability and high scalability can save us a lot of time and effort.

Let's analyze it.

A windows service is regarded as an object and has the following basic behaviors:

Action: Execute the action. (what does this service do)

The same behavior, different implementation logic, a typical factory model.

Next, we will define two windows Service Classes

public class OneTask : IWindowTask
    {
        public void Run(params object[] parms)
        {
Console. WriteLine ("I am the first window simulation service. The first one ");
        }
    }

public class TwoTask:IWindowTask
    {
        public void Run(params object[] parms) {
Console. WriteLine ("I am the second window simulation service. The second is the second ");
        }
    }

And the interface that limits its behavior

Public interface IWindowTask

{

Void Run (params object [] parms );

}

Data Table

Add two records

Factory

public class TaskFactory
    {
        static Hashtable ht = Hashtable.Synchronized(new Hashtable());
 
        public static IWindowTask GetTask(string classPath, IList parms) {
            if (ht[classPath] != null)
                return (IWindowTask)ht[classPath];
            else {
                //var taskInstance = Activator.CreateInstance(Type.GetType(classPath));
                //var taskInstance = System.Reflection.Assembly.Load("MyWindowServiceFramwork").CreateInstance(classPath);
                object taskInstance=null;
                    taskInstance = Type.GetType(classPath).GetConstructor(Type.EmptyTypes).Invoke(null);
                ht[classPath] = taskInstance;
                return (IWindowTask)taskInstance;
            }
        }
        public static IWindowTask GetTask(string classPath) {
            return GetTask(classPath, null);
        }
    }

Enumeration

public enum InterValType { 
        second=1,
        minute=2,
        hour=3,
        day=4,
        week=5,
        month=6
    }

// Add a task class ID attribute to the scheduled control.
class MyTime : System.Timers.Timer {
            public int TaskID { get; set; }
        }
private static void NewMethod1()
        {
            MyPractiseEntities enty = new MyPractiseEntities();
// Obtain all valid tasks.
            var tasks = enty.MyTask.Where(x => x.enable == true);
            foreach (var item in tasks)
            {
                MyTime mytime = new MyTime();
Mytime. TaskID = item. ID; // pay the task ID to the current scheduled class ID
Mytime. Start (); // Start. The default interval is 100 milliseconds.
 
// Execute at intervals. It can be understood that each Timer control is a new thread.
                mytime.Elapsed += delegate(object sender, System.Timers.ElapsedEventArgs e)
                {
// Record the logical operation time, used to calculate the interval of the next running of this method.
                    System.Diagnostics.Stopwatch stop = new System.Diagnostics.Stopwatch();
                    stop.Start();
 
                    MyPractiseEntities enty2 = new MyPractiseEntities();
                    var currentTimer = sender as MyTime;
// The database object must be retrieved again through the current time control. If you write the item directly (see foreach at the upper level), the obtained item is always the last of the tasks set.
                    var currentitem = enty2.MyTask.Where(x => x.ID == currentTimer.TaskID).FirstOrDefault();
// If the current task meets the execution Conditions
                    if (currentitem.LastRunTime <= DateTime.Now && (currentitem.NextRunTime == null || currentitem.NextRunTime <= DateTime.Now))
                    {
CurrentTimer. Stop (); // pause the current task
// Fill in all parameters of the current task
                        var itemParameter = enty2.MyTaskParameter.Where(x => x.TaskID == currentitem.ID).ToList();
                        Func<IList<MyTaskParameter>, object[]> toObjects=x=>{
                            object[] objs =new object[ x.Count];
                            for (int i = 0; i < x.Count; i++)
                            {
                                objs[i] = x[i].ParmValue;
                            }
                            return objs;
                        };
// Obtain and execute
// Use the factory to reflect the task class to be executed and convert it to an interface object/
                        IWindowTask itask = TaskFactory.GetTask(currentitem.ClassPath);
// Execute
                        itask.Run(toObjects(itemParameter));
 
                        System.Threading.Thread.Sleep(2000);
 
// Update the next execution time
                        Func<int, InterValType, double> plusSecond = (intervalue, intervalueType) =>
                        {
                            var temp = 0;
                            switch ((int)intervalueType)
                            {
                                case 1: temp = currentitem.Interval.Value; break;
                                case 2: temp = currentitem.Interval.Value * 60; break;
                                case 3: temp = currentitem.Interval.Value * 60 * 60; break;
                                case 4: temp = currentitem.Interval.Value * 60 * 60 * 24; break;
                            }
                            return temp;
                        };
// Read the configuration file to obtain the time interval
                        var tempsecond = plusSecond(currentitem.Interval.Value, (InterValType)currentitem.IntervalType.Value);
 
 
                        DateTime d1 = currentitem.NextRunTime.Value;
                        currentitem.NextRunTime = d1.AddSeconds(tempsecond);
                        currentitem.LastRunTime = DateTime.Now;
Enty2.SaveChanges (); // updates the status of a task.
 
Stop. Stop (); // monitoring stop
// The interval between the next execution of the time control is the configuration interval minus the running duration.
                        currentTimer.Interval = tempsecond * 1000 - stop.ElapsedMilliseconds;
// Start time control
                        currentTimer.Start();
 
                        Console.WriteLine(); Console.WriteLine();
                    }
                };
            }
        }

 

Program download: see group sharing search MyWIndowService

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.