• Client 客户端AspNetCore.SignalR 通讯服务器 Quartz 执行任务


    背景

      需要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;
            }
    }
    

      

  • 相关阅读:
    或得最新的采购单号并改变为定长
    javaScript学习之路(1)词法结构
    如何让IE下载时下载内容自动跳转到迅雷等下载软件中
    简单的数据库查询操作
    1.1软件工程概述之软件危机
    SQL基础(巧记范式)
    给程序员的五点建议--如何成为编程高手并以此创业
    License控制解决方案
    MVC+三层+ASP.NET简单登录验证
    我曾七次鄙视自己的灵魂
  • 原文地址:https://www.cnblogs.com/leoxjy/p/9808122.html
Copyright © 2020-2023  润新知