1. 程式人生 > >Client 客戶端AspNetCore.SignalR 通訊服務器 Quartz 執行任務

Client 客戶端AspNetCore.SignalR 通訊服務器 Quartz 執行任務

pub ever sig nal 服務 return jobdetail build completed

背景

  需要Client跑服務在終端間隔執行任務,我的目標是運行在樹莓派上

Client代碼

如果未連接成功時隔3秒重新連接服務器

        public static void Reconnect()
        {
            var isLink = false;
            do
            {
                Thread.Sleep(3000);//3秒
                isLink = Signalr().GetAwaiter().GetResult();
            } while (!isLink);
        }

  通過命令開啟 Quartz 調度器

        public static async Task<bool> Signalr()
        {
            System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
            stopwatch.Start(); //  開始監視代碼運行時間
            var urlstr = "https://localhost:44363//hubs";
            var url = new Uri(urlstr);
            var connection = new HubConnectionBuilder()
                               .WithUrl(url)
                               .Build();
            hubConnection = connection;
            connection.On<int, string>("SendCmd", (cmd, data) =>
            {
                switch (cmd)
                {
                    case 10001:
                        if (scheduler == null)
                        {
                            InJobAsync().Wait();
                        }
                        else
                        {
                            if (scheduler.IsStarted != true)
                            {
                                InJobAsync().Wait();
                            }
                            else
                            {

                                connection.SendAsync("ClientMsg", "正在運行");
                            }
                        }

                        break;
                    case 10010:
                        var send = 10;
                        Int32.TryParse(data, out send);
                        if (scheduler != null)
                            scheduler.Clear();
                        InJobAsync(send).GetAwaiter().GetResult();
                        break;
                    default:
                        connection.SendAsync("ClientMsg", "未知命令");
                        break;
                }
            });
            connection.Closed += e =>
            {
                if (e != null)
                {
                    Console.WriteLine("Connection closed..." + e.Message);
                }
                else
                {
                    Console.WriteLine("開始重連..." + e.Message);

                }
                Reconnect();
                return Task.CompletedTask;
            };
            try
            {
                Console.WriteLine($"開始連接服務器[{urlstr}]");
                await connection.StartAsync();
                stopwatch.Stop(); //  停止監視
                TimeSpan timespan = stopwatch.Elapsed; //  獲取當前實例測量得出的總時間
                double seconds = timespan.TotalSeconds;  //  總秒數
                Console.WriteLine($"耗時:{seconds} 服務器[{urlstr}]連接成功!");
                return true;
            }
            catch (Exception err)
            {
                stopwatch.Stop(); //  停止監視
                TimeSpan timespan = stopwatch.Elapsed; //  獲取當前實例測量得出的總時間
                double seconds = timespan.TotalSeconds;  //  總秒數
                var meg = $"執行時間:{seconds} 連接失敗:{err.Message}";
                Console.WriteLine(meg);
                return false;
            }
        }

  

public static StdSchedulerFactory factory = null;
        public static IScheduler scheduler = null;
        public static async Task InJobAsync(int iInterval = 10)
        {

            if (factory == null)
            {
                factory = new StdSchedulerFactory();
            }
            if (scheduler == null)
            {
                scheduler = await factory.GetScheduler();
            }



            // 啟動任務調度器
            await scheduler.Start();

            IJobDetail job = JobBuilder.Create<FlowerJob>()
                    .WithIdentity("job1", "group1")
                    .WithDescription("定時數據傳送")
                    .Build();
            ISimpleTrigger trigger = (ISimpleTrigger)TriggerBuilder.Create()
                .WithIdentity("trigger1") // 給任務一個名字
                                          //.StartAt(myStartTime) // 設置任務開始時間
                .ForJob("job1", "group1") //給任務指定一個分組
                .WithSimpleSchedule(x => x
                    .WithIntervalInSeconds(iInterval)  //循環的時間
                    .RepeatForever())
                .Build();


            // 開啟任務調度器
            await scheduler.ScheduleJob(job, trigger);

        }

  

Jobs任務

public class FlowerJob : IJob
    {
        public Task Execute(IJobExecutionContext context)
        {
            //Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}執行任務:"+context.JobDetail.Description);

            //邏輯代碼
            
            return Task.CompletedTask;
        }
}

  

Client 客戶端AspNetCore.SignalR 通訊服務器 Quartz 執行任務