C#定时任务采用线程和队列实现
构思:写一个全局的Queue , 然后开一个线程去循环. 不善言语,直接看代码吧!
public class MyQueue
{
public decimal Id { get; set; }
public decimal Type { get; set; }
}
static Queue<MyQueue> TaskQueue = new Queue<MyQueue>();
static void Main(string[] args)
{
ServiceStart();
Console.ReadLine();
}
public static void ServiceStart()
{
Thread TaskThread = new Thread(new ThreadStart(ThreadInvoke));
TaskThread.IsBackground = true;
TaskThread.Start();
}
public static void ThreadInvoke()
{
while (true)
{
string m_time = DateTime.Now.ToString("HH:mm:ss");
if (m_time == Invoke_Time) //判断是否指定时间(Invoke_Time)
{
//InitTaskQueue();//初始化队列
while (TaskQueue.Count > 0)
{
MyQueue m_mq = null;
lock (TaskQueue)
{
m_mq = TaskQueue.Dequeue();
}
//YourMethd(m_mq.UserId, m_mq.FeedTypeId); //调用方法
//Common.Log.Logger.Info(DateTime.Now.ToString()); //记录日志
Thread.Sleep(100);
}
}
Thread.Sleep(100);
}
}
{
public decimal Id { get; set; }
public decimal Type { get; set; }
}
static Queue<MyQueue> TaskQueue = new Queue<MyQueue>();
static void Main(string[] args)
{
ServiceStart();
Console.ReadLine();
}
public static void ServiceStart()
{
Thread TaskThread = new Thread(new ThreadStart(ThreadInvoke));
TaskThread.IsBackground = true;
TaskThread.Start();
}
public static void ThreadInvoke()
{
while (true)
{
string m_time = DateTime.Now.ToString("HH:mm:ss");
if (m_time == Invoke_Time) //判断是否指定时间(Invoke_Time)
{
//InitTaskQueue();//初始化队列
while (TaskQueue.Count > 0)
{
MyQueue m_mq = null;
lock (TaskQueue)
{
m_mq = TaskQueue.Dequeue();
}
//YourMethd(m_mq.UserId, m_mq.FeedTypeId); //调用方法
//Common.Log.Logger.Info(DateTime.Now.ToString()); //记录日志
Thread.Sleep(100);
}
}
Thread.Sleep(100);
}
}