using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading;
using TRS.Export.BLL;
using TRS.Export.Business;
using TRS.Export.Common;
using TRS.Export.Constant;
using TRS.Export.Entity;
using TRS.Export.FrameEntity.Enums;
using TRS.Export.FrameProvider;
using TRS.Export.Param.Bases;
using TRS.Export.Param.Enums;
using TRS.Export.Scheduler.Interfaces;

namespace TRS.Export.Scheduler.Schedulers.Business
{
public class BusinessTaobaoEventScheduler : IScheduler
{
private readonly TBD_EventLogBLL m_objEventLogBLL = new TBD_EventLogBLL();

private readonly TaobaoEventBusiness m_objEventBusiness = new TaobaoEventBusiness();

private readonly BackupTableBusiness m_objBackupBusiness = new BackupTableBusiness();

private readonly string m_HttpResolve = ConfigurationManager.AppSettings["HttpResolve"];

private readonly string m_PCSReceiveCodes = ConfigurationManager.AppSettings["PCSReceiveCodes"];

private const int top = 1000;

private OrderByEnum orderByEnum = OrderByEnum.Asc;

delegate void AsyncExecute(object obj);

public int SleepInterval { get; set; }

public string[] Args { get; set; }

public BusinessTaobaoEventScheduler()
{
SleepInterval = 500;
}
//Business.BusinessTaobaoEventScheduler|LOGISTICS_DISPATCHED#后缀$0,1,2,3,4/5,6,7,8,9
public void Execute()
{
if (Args == null || Args.Length == 0)
{
return;
}
//Args=LOGISTICS_DISPATCHED#后缀$0,1,2,3,4/5,6,7,8,9
//eventType=LOGISTICS_DISPATCHED#后缀$0,1,2,3,4/5,6,7,8,9
string[] eventType = Args[0].Split('|');
if (eventType == null || eventType.Length == 0)
{
return;
}

if (eventType.Length == 1)
{
if (eventType[0].IndexOf("#") < 0)//以EventType分线程
{
ExecuteByEventType(eventType[0]);
}
else if (eventType[0].IndexOf("后缀") > -1)//以EventType+LogID最后一位分线程
{ //array=0,1,2,3,4/5,6,7,8,9
string[] array = eventType[0].Substring(eventType[0].IndexOf("后缀") + 3).Split('/');
for (int i = 0; i < array.Length; i++)
{
if (StaticConstant.ASYNC)
{
AsyncExecute async = new AsyncExecute(ExecuteBySuffix);

async.BeginInvoke(new string[] { eventType[0].Split('#')[0], array[i] }, AsyncCallback, async);
}
else
{
Thread thread = new Thread(new ParameterizedThreadStart(ExecuteBySuffix));
thread.Name = string.Format("报文解析后台Job-{0}", array[i]);
thread.Start(new string[] { eventType[0].Split('#')[0], array[i] });
}
}
}
else if (eventType[0].IndexOf("的地") > -1)//以EventType+DestinationName分线程
{
string[] array = eventType[0].Substring(eventType[0].IndexOf("的地") + 3).Split('/');
for (int i = 0; i < array.Length; i++)
{
if (StaticConstant.ASYNC)
{
AsyncExecute async = new AsyncExecute(ExecuteByDestinationName);

async.BeginInvoke(new string[] { eventType[0].Split('#')[0], array[i] }, AsyncCallback, async);
}
else
{
Thread thread = new Thread(new ParameterizedThreadStart(ExecuteByDestinationName));
thread.Name = string.Format("报文解析后台Job-{0}", eventType[0].Split('#')[0] + "-" + array[i]);
thread.Start(new string[] { eventType[0].Split('#')[0], array[i] });
}
}
}
}
else
{
for (int i = 0; i < eventType.Length; i++)//以EventType分线程
{
if (StaticConstant.ASYNC)
{
AsyncExecute async = new AsyncExecute(ExecuteByEventType);

async.BeginInvoke(eventType[i], AsyncCallback, async);
}
else
{
Thread thread = new Thread(new ParameterizedThreadStart(ExecuteByEventType));
thread.Name = string.Format("报文解析后台Job-{0}", eventType[i]);
thread.Start(eventType[i]);
}
}
}

Console.ReadKey();
}

public void AsyncCallback(IAsyncResult result)
{
AsyncExecute async = (AsyncExecute)result.AsyncState;

async.EndInvoke(result);
}

public void ExecuteByEventType(object obj)
{
while (true)
{
try
{
string threadName = string.Format("报文解析后台Job-{0}", obj);

new ThreadMonitorBusiness().CallbackThread(threadName);

WhereHelper<TBD_EventLog> where = new WhereHelper<TBD_EventLog>();
where.ApeendAnd(a => a.SuccessFlag == 0 && a.ActionTimes < 5);
where.ApeendAnd(a => a.EventType == obj.ToString());

OrderByHelper<TBD_EventLog> orderBy = new OrderByHelper<TBD_EventLog>(a => a.ActionTime, orderByEnum);

List<TBD_EventLog> lstEventLog = m_objEventLogBLL.Select(where, top, null, orderBy);
if (lstEventLog == null || lstEventLog.Count == 0)
{
Console.WriteLine("当前线程:[{0}],没有数据,等待{1}秒后继续...{2}", threadName, 60, DateTime.Now);
Thread.Sleep(60 * 1000);

continue;
}

foreach (var item in lstEventLog)
{
Execute(item);

Console.WriteLine("当前线程:[{0}],等待{1}秒后继续...{2}", threadName, 10 / 1000.00, DateTime.Now);
Thread.Sleep(10);
}

Console.WriteLine("当前线程:[{0}],等待{1}秒后继续...{2}", threadName, SleepInterval / 1000, DateTime.Now);

Thread.Sleep(SleepInterval);
}
catch (Exception ex)
{
new EmailBusiness().SendExceptionEmail(ex);
}
}
}

public void ExecuteByDestinationName(object obj)
{
while (true)
{
try
{
string[] array = obj as string[];
if (array == null || array.Length < 2)
{
break;
}

string threadName = string.Format("报文解析后台Job-{0}-{1}", array[0], array[1]);

new ThreadMonitorBusiness().CallbackThread(threadName);

WhereHelper<TBD_EventLog> where = new WhereHelper<TBD_EventLog>();
where.ApeendAnd(a => a.SuccessFlag == 0 && a.ActionTimes < 5);
if (array.Length > 0)
{
where.ApeendAnd(a => a.EventType == array[0]);
}
if (array.Length > 1)
{
where.ApeendAnd(a => a.DestinationName.In(array[1].Split(',')));
}

OrderByHelper<TBD_EventLog> orderBy = new OrderByHelper<TBD_EventLog>(a => a.ActionTime, orderByEnum);

List<TBD_EventLog> lstEventLog = m_objEventLogBLL.Select(where, top, null, orderBy);
if (lstEventLog == null || lstEventLog.Count == 0)
{
Console.WriteLine("当前线程:[{0}],没有数据,等待{1}秒后继续...{2}", threadName, 60, DateTime.Now);
Thread.Sleep(60 * 1000);

continue;
}

foreach (var item in lstEventLog)
{
Execute(item);

Console.WriteLine("当前线程:[{0}],等待{1}秒后继续...{2}", threadName, 10 / 1000.00, DateTime.Now);
Thread.Sleep(10);
}

Console.WriteLine("当前线程:[{0}],等待{1}秒后继续...{2}", threadName, SleepInterval / 1000, DateTime.Now);

}
catch (Exception ex)
{
new EmailBusiness().SendExceptionEmail(ex);
}
}
}

public void ExecuteBySuffix(object obj)
{
while (true)
{
try
{
string[] array = obj as string[];
if (array == null || array.Length < 2)
{
break;
}

string threadName = string.Format("报文解析后台Job-{0}-{1}", array[0], array[1]);

new ThreadMonitorBusiness().CallbackThread(threadName);

WhereHelper<TBD_EventLog> where = new WhereHelper<TBD_EventLog>();
where.ApeendAnd(a => a.ActionTime < DateTime.Now);
where.ApeendAnd(a => a.SuccessFlag == 0 && a.ActionTimes < 5);
if (array.Length > 0)
{
where.ApeendAnd(a => a.EventType == array[0]);
}
if (array.Length > 1)
{

//防止并发处理的小措施
where.ApeendAnd(a => a.LogID.Right(array[1].Split(',')));
}

OrderByHelper<TBD_EventLog> orderBy = new OrderByHelper<TBD_EventLog>(a => a.ActionTime, orderByEnum);

List<TBD_EventLog> lstEventLog = m_objEventLogBLL.Select(where, top, null, orderBy);
if (lstEventLog == null || lstEventLog.Count == 0)
{
Console.WriteLine("当前线程:[{0}],没有数据,等待{1}秒后继续...{2}", threadName, 60, DateTime.Now);
Thread.Sleep(60 * 1000);

continue;
}

foreach (var item in lstEventLog)
{
Execute(item);

Console.WriteLine("当前线程:[{0}],等待{1}秒后继续...{2}", threadName, 10 / 1000.00, DateTime.Now);
Thread.Sleep(10);
}

Console.WriteLine("当前线程:[{0}],等待{1}秒后继续...{2}", threadName, SleepInterval / 1000, DateTime.Now);

}
catch (Exception ex)
{
new EmailBusiness().SendExceptionEmail(ex);
}
}
}

public void Execute(TBD_EventLog eventLog)
{
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
watch.Start();

bool pcs = false;
if (!m_PCSReceiveCodes.IsNullOrEmpty())
{
string[] codes = m_PCSReceiveCodes.Split('|');
foreach (var code in codes)
{
if (eventLog.EventContent.IndexOf(code) > -1)
{
//pcs = true;
}
}
}

if (pcs)
{
string eventContent = eventLog.EventContent;
string destinationName = StringHelper.GetValueByCutStr(ref eventContent, "<consoWarehouseCode>", "</consoWarehouseCode>", false, false);

ExecuteSuccess(eventLog.LogID.Value, 1, destinationName);

Console.WriteLine("当前订单为PCS:[{0}],等待{1}秒后继续...{2}", eventLog.TradeOrderId, 000 / 1000.00, DateTime.Now);

return;
}
else
{

}

ResponseParam response = null;

if (!m_HttpResolve.IsNullOrEmpty())
{
string result = new HttpHelper().Execute(m_HttpResolve, "{\"logId\":" + eventLog.LogID + ",\"appKey\":\"trTaoBaoV02\"}");
if (!result.IsNullOrEmpty())
{
response = JsonConvert.DeserializeObject<ResponseParam>(result);
}
}
else
{
response = m_objEventBusiness.TABAO_EVENT(eventLog);
}

watch.Stop();

if (response == null || !response.success)
{
if (response.result == "2" && eventLog.ActionTimes.Value > 3)
{
ExecuteSuccess(eventLog.LogID.Value);
}
else
{
ExecuteFailure(eventLog.LogID.Value, eventLog.ActionTimes.Value, response.msg);
}

Console.WriteLine("交易订单:{0}分析失败!耗时:{1} {2} {3}", eventLog.TradeOrderId, watch.ElapsedMilliseconds / 1000.00, response == null ? "" : response.msg, DateTime.Now);
}
else
{
ExecuteSuccess(eventLog.LogID.Value);

Console.WriteLine("交易订单:{0}分析成功!耗时:{1} {2} {3}", eventLog.TradeOrderId, watch.ElapsedMilliseconds / 1000.00, response == null ? "" : response.msg, DateTime.Now);
}
}

public void ExecuteFailure(long logID, int actionTimes, string exception)
{
TBD_EventLog update = new TBD_EventLog();
update.LogID = logID;
update.ActionTimes = actionTimes + 1;
update.Exception = exception;
update.ActionTime = DateTime.Now;
if (actionTimes >= 4)
{
update.SuccessFlag = -1;
}

m_objEventLogBLL.Update(update);
}

public void ExecuteSuccess(long logID, int it = 0, string destinationName = null)
{
TBD_EventLog update = new TBD_EventLog();
update.LogID = logID;
update.SuccessFlag = 1;
update.ActionTime = DateTime.Now;
update.IT = it;
if (!destinationName.IsNullOrEmpty())
{
update.DestinationName = destinationName;
}

m_objEventLogBLL.Update(update);

ResponseParam response = m_objBackupBusiness.BackupTable(update);
if (response.success == false)
{
update = new TBD_EventLog();
update.LogID = logID;
update.UpdateTime = DateTime.Now;
update.Exception = response.msg ?? "";

m_objEventLogBLL.Update(update);
}
}
}
}

TWX 比较好的多线程使用实例的更多相关文章

  1. (转) C#多线程赛跑实例

    专于:http://blog.csdn.net/lidatgb/article/details/8363035 结合上篇<多线程的基础>,这次我们写一个多线程的赛跑实例,内容很简单:超人和 ...

  2. vc 基于对话框多线程编程实例——线程之间的通信

     vc基于对话框多线程编程实例——线程之间的通信 实例:

  3. C#多线程编程实例 螺纹与窗口交互

    C#多线程编程实例 螺纹与窗口交互 代码: public partial class Form1 : Form { //声明线程数组 Thread[] workThreads = new Thread ...

  4. c# 多线程 创建对象实例

    本次的标题是我在写单例模式的博客时遇到的问题,所以今天专门写了的demo让自己记住怎么简单的使用多线程. 一直纠结的是怎么在for循环中多次实例化对象,好复现单例模式在没有加锁的情况下出现多个实例对象 ...

  5. linux下C语言多线程编程实例

    用一个实例.来学习linux下C语言多线程编程实例. 代码目的:通过创建两个线程来实现对一个数的递加.代码: //包含的头文件 #include <pthread.h> #include ...

  6. Java单线程多实例和多线程多实例

    最近写了一个程序,是采用多线程往redis里面写入数据,想统计一下一共写了多少条数据,于是用了一个static的全局变量count来累加,这块代码抽象出来就是这样的: public class Mul ...

  7. C#多线程编程实例 线程与窗体交互

    C#多线程编程实例 线程与窗体交互 代码: public partial class Form1 : Form { //声明线程数组 Thread[] workThreads = ]; public ...

  8. java多线程编程实例

    [转]这篇文章主要介绍了java多线程编程实例,分享了几则多线程的实例代码,具有一定参考价值,加深多线程编程的理解还是很有帮助的,需要的朋友可以参考下. 1.三个售票窗口同时出售20张票程序分析:   ...

  9. Java 多线程 简单实例 (Runnable)

    1.多线程实例 package second; public class A implements Runnable { public char stat = '*'; public void run ...

随机推荐

  1. python中的str()与eval函数

    author:headsen chen   date:2018-04-09   10:48:22 eval函数是把str转化成list.dict.tuple str函数把list,dict,tuple ...

  2. 【BZOJ2039】[2009国家集训队]employ人员雇佣 最小割

    [BZOJ2039][2009国家集训队]employ人员雇佣 Description 作为一个富有经营头脑的富翁,小L决定从本国最优秀的经理中雇佣一些来经营自己的公司.这些经理相互之间合作有一个贡献 ...

  3. iOS tableview滑动到底部自动加载,向上拽加载

    - (void)scrollViewDidScroll:(UIScrollView *)aScrollView { CGPoint offset = aScrollView.contentOffset ...

  4. Web移动端使用localStorage缓存Js和css文件 | 强制不要缓存

    1.尽量不把js放在onload事件中,而是放在由用户主动触发的事件 2.加时间戳,时间不同则会加载js而非使用缓存 强制不要缓存: <meta http-equiv=Cache-Control ...

  5. 《JAVA多线程编程核心技术》 笔记:第一章

    一.基本概念理解:1.1.进程和线程的理解1.2.同步和异步的理解(阻塞模式和非阻塞模式)1.3 线程间共享变量和不共享变量二.多线程的实现方式和构造方法:2.1 实现方式:2个2.2 构造方法:8个 ...

  6. URAL 2040 Palindromes and Super Abilities 2(回文树)

    Palindromes and Super Abilities 2 Time Limit: 1MS   Memory Limit: 102400KB   64bit IO Format: %I64d ...

  7. 我的Android进阶之旅------>Java全角半角的转换方法

    一中文全角和半角输入的区别 1全角指一个字符占用两个标准字符位置 2半角指一字符占用一个标准的字符位置 3全角与半角各在什么情况下使用 4全角和半角的区别 5关于全角和半角 6全角与半角比较 二转半角 ...

  8. unix 全缓冲、行缓冲、无缓冲

    基于流的操作最终会调用read或者write函数进行I/O操作.为了使程序的运行效率最高,流对象通常会提供缓冲区,以减少调用系统I/O库函数的次数. 基于流的I/O提供以下3种缓冲: 全 缓冲:直到缓 ...

  9. Django基础(ORM)

    数据库与ORM 数据库的配置 1    django默认支持sqlite,mysql, oracle,postgresql数据库.  <1> sqlite django默认使用sqlite ...

  10. ServiceModel 元数据实用工具 (Svcutil.exe)

    ServiceModel 元数据实用工具用于依据元数据文档生成服务模型代码,以及依据服务模型代码生成元数据文档 一.SvcUtil.exe ServiceModel 元数据实用工具可在 Windows ...