使用Quartz.Net定时发送消息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
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 @   听海漫步  阅读(379)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示