使用Quartz.Net定时发送消息

using Microsoft.EntityFrameworkCore.Internal;
using MongoDB.Bson;
using Newtonsoft.Json;
using Player.Common;
using Player.Common1;
using Player.DBUtility;
using Player.Infrastructure.Entities.Chat;
using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Player.Web.AutoServer
{
    /// <summary>
    /// 定时查询机器人
    /// </summary>
    public class TimerRobotJob : IJob
    {
        /// <summary>
        /// 调度器
        /// </summary>
        public static IScheduler scheduler = null;

        public async Task Execute(IJobExecutionContext context)
        {
            try
            {
                Console.WriteLine($"================开始刷新机器人任务 {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}================");
                scheduler = context.Scheduler; //获取调度器
                await RobotChatTask(context);
            }
            catch (Exception ex)
            {
                LogHelper.DebugLog("任务程序报错:机器人聊天" + ex.Message);
            }
        }

        /// <summary>
        /// 机器人聊天
        /// </summary>
        private async Task RobotChatTask(IJobExecutionContext context)
        {
            var sort = new BsonDocument() { new BsonElement("createTime", -1) };//排序
            var list = new MongoDBHelper<ChatRobots>().QueryAll((t) => t.IsEnable && t.IsChat && t.SayTimes.ToList().Contains(DateTime.Now.Hour), sort);
            if(list != null)
            {
                foreach (var item in list)
                {
                    if(context != null && context.Scheduler.CheckExists(new JobKey(item.Id.ToString())).Result)
                    {
                        continue;//机器人已存在定时任务,则不需要绑定任务
                    }
                    string cronTime = item.Interval < 60 ? $"0/{item.Interval} * * * * ? " : $"0 0/{item.Interval / 60} * * * ? ";//为true按秒间隔  为false按分钟间隔
                    await CreateJob<TimerSendMsgJob>($"{item.Id}", $"TimerSendRobotJob", cronTime); //定时发送聊天任务
                }
            }
        }

        /// <summary>
        /// 创建运行的调度器
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="name"></param>
        /// <param name="group"></param>
        /// <param name="cronTime"></param>
        /// <returns></returns>
        public static async Task CreateJob<T>(string name, string group, string cronTime) where T : IJob
        {
            //创建一个作业
            var job = JobBuilder.Create<T>()
                .WithIdentity(name,group)
                .Build();

            //创建一个触发器
            var tigger = (ICronTrigger)TriggerBuilder.Create()
                .WithIdentity(name,group)
                .StartNow()
                .WithCronSchedule(cronTime)
                .Build();
            //把作业和触发器放入调度器中
            await scheduler.ScheduleJob(job, tigger);
        }
    }

    /// <summary>
    /// 定时机器人发言
    /// </summary>
    public class TimerSendMsgJob : IJob
    {
        public async Task Execute(IJobExecutionContext context)
        {
            try
            {
                string key_id = context.JobDetail.Key.Name; //任务的名称 机器人表objectid
                var info = new MongoDBHelper<ChatRobots>().QueryByFirst((t) => t.Id == new ObjectId(key_id) && t.IsEnable && t.IsChat && t.SayTimes.ToList().Contains(DateTime.Now.Hour));
                if (info != null)
                {
                    double seconds = (context.NextFireTimeUtc - context.FireTimeUtc).Value.TotalSeconds;//下次触发时间 - 当前触发时间 = 间隔时间
                    if (info.Interval != Math.Round(seconds))
                    {
                        //如果两次间隔时间不同,则重新设置触发器的时间
                        if (await context.Scheduler.DeleteJob(new JobKey(key_id, "TimerSendRobotJob")))
                        {
                            string cronTime = info.Interval < 60 ? $"0/{info.Interval} * * * * ? " : $"0 0/{info.Interval / 60} * * * ? ";//为true按秒间隔  为false按分钟间隔
                            await TimerRobotJob.CreateJob<TimerSendMsgJob>(key_id, "TimerSendRobotJob", cronTime);
                        }
                    }
                    int radom = new Random().Next(info.Quotation.Length);//根据机器人语录产生一个随机数
                    await SendMQMsg("RobotChatExchange", "RobotMsgChatQueue", new
                    {
                        info.ChatRoomId,            //房间id
                        info.RobotVIPLevel,         //VIP等级
                        info.RobotNickName,         //昵称 
                        msg = info.Quotation[radom],//随机消息
                        time = DateTime.Now,        //消息时间
                    });
                }
                else
                {
                    await context.Scheduler.DeleteJob(new JobKey(key_id, "TimerSendRobotJob")); //本次小时时间段不需要发言,移除定时任务
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(LogType.InfoLog, $"任务程序报错:机器人聊天{ex}");
            }
        }

        /// <summary>
        /// 发送MQ消息
        /// </summary>
        /// <param name="exchangeName">通道名称</param>
        /// <param name="queueName">消息名称</param>
        /// <param name="msg">消息内容</param>
        private async Task SendMQMsg(string exchangeName, string queueName, object data)
        {
            await Task.Run(() =>
            {
                string msg = Utils.ToJson(data);
                new RabbitMQHelper(exchangeName).SendMsg(queueName, msg);
                LogHelper.Info(LogType.InfoLog, $"聊天消息:{msg}");
            });
        }
    }
}
posted @ 2020-06-12 15:55  听海漫步  阅读(368)  评论(0编辑  收藏  举报