自写任务调度模型

自写任务调度模型,控制台程序演示。

首先:创建一个线程,线程启动调度平台。调度平台先创建调度集合。并将调度集合中的每个调度的执行时间进行设定。

其次,线程中再启动一个100MS的定时器,在定时器中判断调度是否正在执行,如果没有执行,则执行调度,否则不执行。

最后,判断当前时间与调度的计划执行时间是否一致,如果一致,则启动新的线程,执行调度。后台运行调度。

1、入口函数,启动新线程,启动调度平台。

class Program
{
static void Main(string[] args)
{

Perform perform = new Perform();
ThreadStart start = new ThreadStart(perform.Start);
Thread thread = new Thread(start);
thread.IsBackground = true;
thread.Start();

Console.ReadKey();
}
}

2、Perform实现如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleAllDemo
{
public class Perform
{
private List<IRunner> runners = new List<IRunner>();
private Timer timer = null;
public void Start()
{
runners = getRunner();
if (runners.Count < 1)
{
return;
}
if (timer != null)
{
return;
}
timer = new Timer((new TimerCallback(Run)), null, 0, 100);
}

private List<IRunner> getRunner()
{
IRunner runner1 = new Runner("First");
runners.Add(runner1);
IRunner runner2 = new Runner("Second");
runners.Add(runner2);
return runners;
}

private void Run(object o)
{
foreach (IRunner item in runners)
{
if (DateTime.Now.Second % 5 == 0)
{
if (!item.IsRunning)
{
item.run();
}
}
}
}
}
}

3、执行调度接口

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleAllDemo
{
public interface IRunner
{
void run();

DateTime BeginTime { get; set; }

string Name { get; }
bool IsRunning { get; }
}

public class Runner : IRunner
{
private bool isRunning = false;
private string name;
private DateTime beginTime;

public Runner(string name)
{
this.name = name;
}

public void run()
{
Thread thread = new Thread(new ThreadStart(this.Begin));
thread.Name = this.Name;
thread.IsBackground = true;
thread.Start();
}

private void Begin()
{
isRunning = true;
Thread.Sleep(1000);
Console.WriteLine(name + " is starting to run...");
isRunning = false;
}


public bool IsRunning
{
get { return this.isRunning; }
}

public string Name
{
get { return this.name; }
}

public DateTime BeginTime
{
get { return this.beginTime; }
set { this.beginTime = value; }
}
}

}

原文地址:https://www.cnblogs.com/baoku/p/4953483.html