public void AgentTimerBuild(Agent agent) { agent.Timers = new List<Timer>(); foreach (var site in TaskQueue.sites) {//遍历所有站点 System.Threading.Thread.Sleep(2000); ProcessTesk(site, agent);//从任务列表中取出待执行的任务分配给代理端执行 Timer timer = new Timer(1000 * site.GrabInterval); timer.Elapsed += delegate { ProcessTesk(site, agent); }; timer.Enabled = true; agent.Timers.Add(timer); } }
private void ProcessTesk(Site site, Agent agent) { var task = TaskQueue.tasks.Where(d => d.Status == eTaskStatus.Standby && d.Site == site.Name).FirstOrDefault();//取出待执行的第一条任务 if (task != null) {//取出任务后 task.Status = eTaskStatus.Executing;//改变任务状态为执行中,以免重复执行 task.HandlerAgent = agent.Name; task.HandlerTime = DateTime.Now; Clients.Client(agent.ConnectionId).castTesk(task);//将任务推送给代理端 BroadcastRanderTask(); } else { var executingTask = TaskQueue.tasks.Where(d => d.Status == eTaskStatus.Executing && d.Site == site.Name).OrderBy(d => d.HandlerTime).FirstOrDefault(); if (executingTask != null && (DateTime.Now - executingTask.HandlerTime).TotalMinutes > 2) { executingTask.HandlerAgent = agent.Name; executingTask.HandlerTime = DateTime.Now; Clients.Client(agent.ConnectionId).castTesk(executingTask); BroadcastRanderTask(); } } }
/// <summary> /// 注册为一个代理端,用来执行服务端的任务 /// </summary> /// <param name="name"></param> public void RegisterAgent(string name) { Groups.Add(Context.ConnectionId, "agent");//加入到代理组 var agent = TaskQueue.agents.SingleOrDefault(d => d.Name == name); if (agent != null) { agent.ConnectionId = Context.ConnectionId; agent.Online = true; if (agent.Timers != null) foreach (var timer in agent.Timers) timer.Start(); Clients.Group("broad").agentList(TaskQueue.agents); } else { var newagent = new Agent { ConnectionId = Context.ConnectionId, Name = name, Online = true }; TaskQueue.agents.Add(newagent);//加入到代理缓存中 Clients.Group("broad").agentList(TaskQueue.agents);//广播给前端,用来更新页面的代理列表 AgentTimerBuild(newagent);//开始分配任务的Timer事件 } }