110,529
社区成员
发帖
与我相关
我的任务
分享
class Program
{
static void Main(string[] args)
{
System.Timers.Timer timer = new System.Timers.Timer(5000);
timer.Elapsed += (sender, e) =>
{
Program p = new Program();
Console.WriteLine(p.GetRandomNumber());
};
timer.Start();
Console.Read();
}
static DateTime dt = DateTime.Now;
static int random;
Random r = new Random();
public int GetRandomNumber()
{
TimeSpan ts = DateTime.Now - dt;
if (ts.TotalSeconds >= 20 || random == 0)//这里把ts.TotalSeconds换成ts.TotalMinutes就是分钟了
{
dt = DateTime.Now;
random = r.Next(0, (int)(dt - new DateTime(dt.Year, 1, 1)).TotalMinutes);
}
return random;
}
}
public class RandomValueGenerater
{
public DateTime LastTime { set; get; }
public TimeSpan SameTime { set; get; }
public int LastRandomValue { set; get; }
private Random _random;
public RandomValueGenerater(TimeSpan span)
{
SameTime = span;
_random = new Random((int)DateTime.Now.Ticks);
}
public int GetNext()
{
if (DateTime.Now - LastTime > SameTime)
{
LastTime = DateTime.Now;
LastRandomValue = _random.Next();
}
return LastRandomValue;
}
}
static void Main(string[] args)
{
RandomValueGenerater r = new RandomValueGenerater(new TimeSpan(0, 0, 5));
while (true)
{
Console.WriteLine(r.GetNext());
Thread.Sleep(1000);
}
}