|
這個(gè)源之于一個(gè)朋友問(wèn)我的一個(gè)問(wèn)題,他說(shuō)他們的需求是在一天之內(nèi)隨機(jī)抽取數(shù)據(jù)生成訂單,還不能讓客戶(hù)看出來(lái)。 隨機(jī)生成的訂單還分概率抽取不一定的狀態(tài)值,那么根據(jù)我之前寫(xiě)的定時(shí)器線(xiàn)程執(zhí)行器,我們?cè)O(shè)計(jì)需要一個(gè)定時(shí)器去執(zhí)行。 那么我們的定時(shí)器坑定需要一直運(yùn)行,包括每天的情況。 創(chuàng)建 SecondsTimerTask 由于是測(cè)試條件下,我們聲明5秒運(yùn)行一次
1 /// <summary> 2 /// 每秒執(zhí)行的任務(wù) 3 /// </summary> 4 public class SecondsTimerTask : TimerTaskBase 5 { 6 /// <summary> 7 /// 定義一秒執(zhí)行一次的 8 /// </summary> 9 public SecondsTimerTask() 10 : base(0, 1000, false) 11 { 12 13 } 14 15 List<int> ints1 = new List<int>() { 1, 2, 3, 4, 5 }; 16 List<int> ints2 = new List<int>() { 6, 7, 8, 9, 10 }; 17 18 string _ActionDay = string.Empty; 19 int _ActionCount = 0; 20 21 public override void Run() 22 { 23 string day = DateTime.Now.ToString("yyyy/MM/dd"); 24 if (!day.Equals(_ActionDay)) 25 { 26 //如果是非本日情況,重置條件 27 //可以根據(jù)自身的條件完成 28 ints1 = new List<int>() { 1, 2, 3, 4, 5 }; 29 ints2 = new List<int>() { 6, 7, 8, 9, 10 }; 30 _ActionDay = day; 31 _ActionCount = 0; 32 } 33 if (_ActionCount == 5) 34 { 35 Console.WriteLine(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss:ffff: ") + "隨機(jī)生成訂單 今日任務(wù)完成"); 36 return; 37 } 38 int ran = new Random(DateTime.Now.Millisecond).Next(0, 100000);//用0到10萬(wàn)為隨機(jī)界限標(biāo)準(zhǔn) 39 if (ran < 70000)//70%的概率這次執(zhí)行需要生產(chǎn)訂單 40 { 41 _ActionCount++; 42 int ranNext = new Random(DateTime.Now.Millisecond).Next(0, 100000);//用0到10萬(wàn)為隨機(jī)界限標(biāo)準(zhǔn) 43 if (ranNext > 40000) 44 { 45 //60%的概率 46 int index = new Random(DateTime.Now.Millisecond).Next(0, ints1.Count); 47 int item = ints1[index]; 48 Console.WriteLine(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss:ffff: ") + "隨機(jī)生成訂單60%的概率: " + item); 49 ints1.RemoveAt(index); 50 } 51 else 52 { 53 ///40%的概率 54 int index = new Random(DateTime.Now.Millisecond).Next(0, ints2.Count); 55 int item = ints2[index]; 56 Console.WriteLine(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss:ffff: ") + "隨機(jī)生成訂單40%的概率: " + item); 57 ints2.RemoveAt(index); 58 } 59 } 60 else 61 { 62 Console.WriteLine(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss:ffff: ") + " 根據(jù)隨機(jī)情況不生成訂單"); 63 } 64 } 65 }
請(qǐng)結(jié)合定時(shí)器線(xiàn)程章節(jié), 1 class Program 2 { 3 4 static void Main(string[] args) 5 { 6 TimerThread timerThread = new TimerThread(); 7 timerThread.AddTask(new SecondsTimerTask()); 8 Console.ReadLine(); 9 } 10 }
我們來(lái)看看結(jié)果
上面的運(yùn)行結(jié)果,大家注意時(shí)間,我是在今日任務(wù)完成的情況下,我直接修改系統(tǒng)時(shí)間為第二天,然后繼續(xù)第二天的任務(wù) 這樣就保證了程序如果一直在運(yùn)行的情況下,完成每日的生成訂單的量。 但是需要注意的是,我沒(méi)有考慮如果程序重啟的情況,需要各位根據(jù)各自的情況進(jìn)行修改~! |
|
|
來(lái)自: 昵稱(chēng)10504424 > 《工作》