/// <summary>开始工作</summary> /// <param name="reason"></param> protected override void StartWork(String reason) { WriteLog("业务开始……"); // 配置APM性能跟踪器 var set = Setting.Current; if (!set.TracerServer.IsNullOrEmpty()) { // 配置指向星尘监控中心 var tracer = new StarTracer(set.TracerServer) { Log = XTrace.Log }; DefaultTracer.Instance = tracer; ApiHelper.Tracer = tracer; DAL.GlobalTracer = tracer; Tracer = tracer; } // 5秒开始,每60秒执行一次 _timer = new TimerX(DoWork1, null, 5_000, 60_000) { Async = true }; // 每天凌晨2点13分执行一次 _timer2 = new TimerX(DoWork2, null, DateTime.Today.AddMinutes(2 * 60 + 13), 24 * 3600 * 1000) { Async = true }; base.StartWork(reason); }
static void ProcessBell(ref String m) { var ch = (Char)7; var p = 0; while (true) { p = m.IndexOf(ch, p); if (p < 0) { break; } if (p > 0) { var str = m.Substring(0, p); if (p + 1 < m.Length) { str += m.Substring(p + 1); } m = str; } //Console.Beep(); // 用定时器来控制Beep,避免被堵塞 if (_timer == null) { _timer = new TimerX(Bell, null, 100, 100); } _Beep = true; //SystemSounds.Beep.Play(); p++; } }
/// <summary>归还</summary> /// <param name="obj"></param> public virtual void Push(T obj) { // 释放后,不再接受归还,因为可能别的线程尝试归还 if (Disposed) { return; } var stack = Stock; // 超过最大值了,启动清理定时器 if (stack.Count > Max) { if (_clearTimers == null) { _clearTimers = new TimerX(ClearAboveMax, null, 0, 120000); } } else { // 没到最大值,关闭定时器? if (stack.Count < Max - 100 && _clearTimers != null) { _clearTimers.Dispose(); _clearTimers = null; } } stack.Push(obj); }
public void CronTest() { XTrace.WriteLine("CronTest"); using var timer = new TimerX(DoAsyncTest2, "CronTest", "1/2 * * * *"); Thread.Sleep(5500); }
static void Main(string[] args) { var builder = new ContainerBuilder(); AhnqIotContainer.Builder = builder; BootStraper.Start(); //Service层启动初始化 BussinessBootStraper.Start(); //Assembly asm = Assembly.ReflectionOnlyLoadFrom("SmartIot.API.Processor.dll"); //Ioc.CurrentIoc.RegisterAssembly(asm); //Ioc.CurrentIoc.RegisterType<ManageDataProcessor, ManageDataProcessor>(); //容器注册完成 //Ioc.CurrentIoc.RegisterDone(); //初始化数据库数据 BussinessBootStraper.InitDatabaseData(); //每10分钟自动释放存一次 _releaseTimerX = new TimerX(obj => Runtime.ReleaseMemory(), null, 5 * 60 * 1000, 10 * 60 * 1000); // ApiService.ServiceMain(); var service = new ApiService(); service.Start(); Console.ReadLine(); }
/// <summary>增加</summary> /// <param name="value">增加的数量</param> /// <param name="usCost">耗时,单位us</param> public void Increment(Int64 value, Int64 usCost) { if (!Enable) { return; } // 累加总次数和总数值 Interlocked.Add(ref _Value, value); Interlocked.Increment(ref _Times); if (usCost > 0) { Interlocked.Add(ref _TotalCost, usCost); } if (_Timer == null) { lock (this) { if (_Timer == null) { _Timer = new TimerX(DoWork, null, Interval, Interval) { Async = true } } ; } } }
public void AsyncTest() { XTrace.WriteLine("AsyncTest"); using var timer = new TimerX(DoAsyncTest, "Stone", 10, 100); Thread.Sleep(1000); }
private TextFileLog(String path, Boolean isfile, String fileFormat = null) { if (!isfile) { LogPath = path; } else { LogFile = path; } if (!fileFormat.IsNullOrEmpty()) { FileFormat = fileFormat; } else { FileFormat = Setting.Current.LogFileFormat; } _Timer = new TimerX(WriteFile, null, 1000, 1000) { Async = true, CanExecute = () => !_Logs.IsEmpty }; }
static void Test2() { var ic = Redis.Create("127.0.0.1", 3); // 简单操作 Console.WriteLine("共有缓存对象 {0} 个", ic.Count); var count = 2000000; Console.WriteLine("准备插入缓存{0:n0}项", count); var sw = Stopwatch.StartNew(); var prg = 0; var t = new TimerX(s => { XTrace.WriteLine("已处理 {0:n0} 进度 {1:p2} 速度 {2:n0}tps", prg, (Double)prg / count, prg * 1000 / sw.ElapsedMilliseconds); }, null, 1000, 1000); var buf = Rand.NextBytes(2800); for (var i = 0; i < count; i++) { var key = "BILL:" + (i + 1).ToString("000000000000"); ic.Set(key, buf, 48 * 3600); prg++; } t.TryDispose(); }
static void TestServer() { // 实例化服务端,指定端口,同时在Tcp/Udp/IPv4/IPv6上监听 var svr = new NetServer { Port = 1234, Log = XTrace.Log }; //svr.Add(new LengthFieldCodec { Size = 4 }); svr.Add <StandardCodec>(); svr.Add <EchoHandler>(); // 打开原始数据日志 var ns = svr.Server; ns.LogSend = true; ns.LogReceive = true; svr.Start(); _server = svr; // 定时显示性能数据 _timer = new TimerX(ShowStat, svr, 100, 1000); }
public static void Initialize() { enabled = false; var cachePath = UserConfiguration.Current.CachePath.GetFullPath(); if (String.IsNullOrEmpty(cachePath)) { return; } cachePath.EnsureDirectory(false); //var expectation = GetExpectation(); //var reality = new String[accessors.Length]; //var filename = Path.Combine(cachePath, "version"); //if (File.Exists(filename)) //{ // var lines = File.ReadAllLines(filename); // Array.Copy(lines, reality, Math.Min(lines.Length, reality.Length)); //} //for (int i = 0; i < reality.Length && i < expectation.Length; i++) //{ // if (reality[i] != expectation[i]) // { // var path = Path.Combine(cachePath, (i + 1).ToString()); // if (Directory.Exists(path)) // { // var tmpPath = path + "." + DateTime.Now.Ticks + ".del"; // Directory.Move(path, tmpPath); // } // } //} //File.WriteAllLines(filename, expectation); _timer = new TimerX(s => { var dirs = Directory.GetDirectories(cachePath, "*.del"); foreach (var dir in dirs) { XTrace.WriteLine("Delete cache directory {0}", dir); Directory.Delete(dir, true); } }, null, 10000, 10 * 60 * 1000); // 每天凌晨3点删除一次所有缓存目录 _timer2 = new TimerX(s => { var dir = UserConfiguration.Current.CachePath.GetFullPath(); foreach (var item in dir.AsDirectory().GetDirectories()) { XTrace.WriteLine("Delete cache directory {0}", item.FullName); item.Delete(true); } }, null, DateTime.Now.Date.AddHours(3), 24 * 60 * 60 * 1000); enabled = true; }
protected override void OnStop() { _timer.TryDispose(); _timer = null; base.OnStop(); }
/// <summary>启动</summary> public override void Start() { var cfg = Config; var ss = cfg.NameServerAddress.Split(";"); //Servers = ss.Select(e => new NetUri(e)).ToArray(); var list = new List <NetUri>(); foreach (var item in ss) { var uri = new NetUri(item); if (uri.Type == NetType.Unknown) { uri.Type = NetType.Tcp; } list.Add(uri); } Servers = list.ToArray(); base.Start(); if (_timer == null) { _timer = new TimerX(DoWork, null, cfg.PollNameServerInterval, cfg.PollNameServerInterval); } }
static void TestClient() { var uri = new NetUri("tcp://::1:1234"); //var uri = new NetUri("tcp://net.newlifex.com:1234"); var client = uri.CreateRemote(); client.Log = XTrace.Log; client.LogSend = true; client.LogReceive = true; client.Received += (s, e) => { XTrace.WriteLine("收到:{0}", e.Packet.ToStr()); }; client.Open(); // 定时显示性能数据 _timer = new TimerX(ShowStat, client, 100, 1000); // 循环发送数据 for (var i = 0; i < 5; i++) { Thread.Sleep(1000); var str = "你好" + (i + 1); client.Send(str); } client.Dispose(); }
static void TestServer() { // 实例化RPC服务端,指定端口,同时在Tcp/Udp/IPv4/IPv6上监听 var svr = new ApiServer(1234); // 注册服务控制器 svr.Register <MyController>(); svr.Register <UserController>(); // 指定编码器 svr.Encoder = new JsonEncoder(); svr.EncoderLog = XTrace.Log; // 打开原始数据日志 var ns = svr.EnsureCreate() as NetServer; //var ns = svr.Server as NetServer; ns.Log = XTrace.Log; ns.LogSend = true; ns.LogReceive = true; svr.Log = XTrace.Log; svr.Start(); _server = svr; // 定时显示性能数据 _timer = new TimerX(ShowStat, ns, 100, 1000); }
static void TestClient() { //var uri = new NetUri("tcp://127.0.0.1:1234"); var uri = new NetUri("tcp://www.armku.com:1234"); var client = uri.CreateRemote(); client.Log = XTrace.Log; client.Received += (s, e) => { var pk = e.Message as Packet; XTrace.WriteLine("收到:{0}", pk.ToStr()); }; //client.Add(new LengthFieldCodec { Size = 4 }); client.Add <StandardCodecDemo>(); // 打开原始数据日志 var ns = client; ns.LogSend = true; ns.LogReceive = true; client.Open(); // 定时显示性能数据 _timer = new TimerX(ShowStat, client, 100, 1000); // 循环发送数据 for (var i = 0; i < 1; i++) { var str = "你好" + (i + 1); var pk = new Packet(str.GetBytes()); client.SendMessageAsync(pk); } }
static void TestServer() { // 实例化服务端,指定端口,同时在Tcp/Udp/IPv4/IPv6上监听 var svr = new MyNetServer { Port = 1234, Log = XTrace.Log, SessionLog = XTrace.Log, StatPeriod = 30, Tracer = new DefaultTracer { Period = 15, Log = XTrace.Log }, #if DEBUG SocketLog = XTrace.Log, LogSend = true, LogReceive = true, #endif }; svr.Start(); _server = svr; // 定时显示性能数据 _timer = new TimerX(ShowStat, svr, 100, 1000) { Async = true }; }
public override void StartWork() { // 要求马上重新加载配置 Setting.Current = null; var set = Setting.Current; // 初始化队列 ServerItem.Init(); if (ServerItem.Queue.Count < 1) { WriteLine("没有正确配置远程地址,停止服务"); Stop(); return; } Svr = new RDPServer(); Svr.Port = set.Port; if (set.Debug) { Svr.Log = XTrace.Log; } Svr.Start(); _timer = new TimerX(Check, null, 10000, 10000); }
public void NormalTest() { var now = DateTime.Now; var count = 0; using var timer = new TimerX(s => { Interlocked.Increment(ref count); //Assert.Equal(s, TimerX.Current); }, null, 1000, 3000, "Test"); Assert.True(timer.Id > 0); Assert.Equal("Test", timer.Scheduler.Name); //Assert.NotNull(timer.Callback); Assert.Null(timer.State); Assert.True(timer.NextTime > now.AddMilliseconds(100)); //Assert.True(timer.NextTime < now.AddMilliseconds(20)); Assert.Equal(0, timer.Timers); Assert.Equal(3000, timer.Period); Assert.False(timer.Async); Assert.False(timer.Absolutely); Thread.Sleep(3050); //Assert.Equal(10, count); //Assert.Equal(10, timer.Timers); }
/// <summary>添加实体对象进入队列</summary> /// <param name="entity"></param> /// <returns></returns> public Boolean Add(IEntity entity) { if (_Timer == null) { _Timer = new TimerX(Work, null, Period, Period); } // 避免重复加入队列 var list = Entities; if (list.Contains(entity)) { return(false); } lock (this) { list = Entities; // 避免重复加入队列 if (list.Contains(entity)) { return(false); } list.Add(entity); } return(true); }
public void AsyncTest2() { XTrace.WriteLine("AsyncTest2"); using var timer = new TimerX(DoAsyncTest2, "Stone2", DateTime.Now, 100); Thread.Sleep(1000); }
/// <summary>服务启动</summary> /// <remarks> /// 安装Windows服务后,服务启动会执行一次该方法。 /// 控制台菜单按5进入循环调试也会执行该方法。 /// </remarks> protected override void StartWork(String reason) { var set = Setting.Current; var svr = new ApiServer(set.Port) { Log = XTrace.Log }; //var ts = new AntService(); //svr.Register(ts, null); svr.Register <AntService>(); AntService.Log = XTrace.Log; // 本地结点 AntService.Local = new IPEndPoint(NetHelper.MyIP(), set.Port); svr.Start(); _server = svr; _clearOnlineTimer = new TimerX(ClearOnline, null, 1000, 10 * 1000); _clearItemTimer = new TimerX(ClearItems, null, 10_000, 3600_000) { Async = true }; base.StartWork(reason); }
/// <summary>设置网页会话状态</summary> /// <param name="sessionid"></param> /// <param name="page"></param> /// <param name="status"></param> /// <param name="user"></param> /// <param name="ip"></param> /// <returns></returns> public static UserOnline SetWebStatus(String sessionid, String page, String status, IManageUser user, String ip) { // 网页使用一个定时器来清理过期 if (_timer == null) { lock (typeof(UserOnline)) { if (_timer == null) { _timer = new TimerX(s => ClearExpire(), null, 0, 30 * 1000) { Async = true } } ; } } if (user == null) { return(SetStatus(sessionid, page, status, 0, null, ip)); } //if (user is IAuthUser user2) user2.Online = true; //(user as IEntity).SaveAsync(1000); return(SetStatus(sessionid, page, status, user.ID, user + "", ip)); }
/// <summary>停止</summary> public void Stop() { if (cs != null) { XTrace.WriteLine("正在关闭连接……"); for (var i = 0; i < cs.Length; i++) { if (cs[i] != null) { try { cs[i].Dispose(); } catch { } } } cs = null; } if (timer != null) { timer.Dispose(); timer = null; } }
/// <summary>加入请求队列</summary> /// <param name="owner">拥有者</param> /// <param name="request">请求的数据</param> /// <param name="remote">远程</param> /// <param name="msTimeout">超时取消时间</param> public virtual Task <Packet> Add(Object owner, Packet request, IPEndPoint remote, Int32 msTimeout) { var now = DateTime.Now; var qi = new Item(); qi.Owner = owner; qi.Request = request; qi.Remote = remote; qi.EndTime = now.AddMilliseconds(msTimeout); qi.Source = new TaskCompletionSource <Packet>(); // 加锁处理,更安全 var qs = Items; lock (qs) { qs.AddLast(qi); } if (_Timer == null) { lock (this) { if (_Timer == null) { _Timer = new TimerX(Check, null, 1000, 1000, "Packet"); } } } return(qi.Source.Task); }
/// <summary>入口方法</summary> public static void Main() { try { stress = new TcpStress(); stress.Config = TcpStressConfig.Current; stress.Config.Show(); stress.Init(); Console.WriteLine("准备就绪!任意键开始……"); Console.ReadKey(true); var sw = Stopwatch.StartNew(); timerShowStatus = new TimerX(ShowStatus, null, 1000, 1000); stress.Start(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } Console.WriteLine("压力测试中!任意键结束……"); Console.ReadKey(true); stress.Stop(); timerShowStatus.Dispose(); }
/// <summary>开始服务</summary> /// <param name="reason"></param> protected override void StartWork(String reason) { // 实例化服务端,指定端口,同时在Tcp/Udp/IPv4/IPv6上监听 var svr = new MyNetServer { Port = 1234, Log = XTrace.Log, Tracer = new DefaultTracer { Period = 15, Log = XTrace.Log }, #if DEBUG SocketLog = XTrace.Log, LogSend = true, LogReceive = true, #endif }; svr.Start(); _Server = svr; _timer1 = new TimerX(s => ShowStat(_Server), null, 1000, 1000) { Async = true }; _timer2 = new TimerX(s => SendTime(_Server), null, 1000, 1000) { Async = true }; base.StartWork(reason); }
/// <summary>开始工作</summary> /// <param name="reason"></param> protected override void StartWork(String reason) { // 配置APM性能跟踪器 var set = Stardust.Setting.Current; if (!set.Server.IsNullOrEmpty()) { // 配置指向星尘监控中心 var tracer = new StarTracer(set.Server) { Log = XTrace.Log }; DefaultTracer.Instance = tracer; ApiHelper.Tracer = tracer; DAL.GlobalTracer = tracer; Tracer = tracer; } InitNetServer(); InitRpcServer(); _timer1 = new TimerX(s => ShowStat(), null, 1000, 1000) { Async = true }; _timer2 = new TimerX(s => SendTime(_netServer), null, 1000, 1000) { Async = true }; base.StartWork(reason); }
/// <summary>异步多次发送数据</summary> /// <param name="session">会话</param> /// <param name="pk">数据包</param> /// <param name="times">次数</param> /// <param name="msInterval">间隔</param> /// <returns></returns> public static Boolean SendMulti(this ISocketRemote session, Packet pk, Int32 times, Int32 msInterval) { if (times <= 1) { session.Send(pk); return(true); } if (msInterval < 10) { for (var i = 0; i < times; i++) { session.Send(pk); } return(true); } var timer = new TimerX(s => { session.Send(pk); // 如果次数足够,则把定时器周期置空,内部会删除 var t = s as TimerX; if (--times <= 0) { t.Period = 0; } }, null, 0, msInterval); return(true); }
/// <summary>打开客户端</summary> public virtual Boolean Open() { if (Active) { return(true); } lock (Root) { if (Active) { return(true); } var ss = Servers; if (ss == null || ss.Length == 0) { throw new ArgumentNullException(nameof(Servers), "未指定服务端地址"); } if (Encoder == null) { Encoder = new JsonEncoder(); } //if (Encoder == null) Encoder = new BinaryEncoder(); if (Handler == null) { Handler = new ApiHandler { Host = this } } ; // 集群 Cluster = InitCluster(); WriteLog("集群:{0}", Cluster); Encoder.Log = EncoderLog; // 控制性能统计信息 var ms = StatPeriod * 1000; if (ms > 0) { if (StatSend == null) { StatSend = new PerfCounter(); } if (StatReceive == null) { StatReceive = new PerfCounter(); } _Timer = new TimerX(DoWork, null, ms, ms) { Async = true }; } return(Active = true); } }