Quartz+TopShelf实现window服务每月1号自动生成报表DingTalk给领导(钉钉群机器人推送).net实现

1、使用VS新建控制台程序 DZMonthCreate

2、使用包管理器NuGet引入  Quartz(版本2.6.1.0)TopShelf(版本4.0.0.0)

3、新建QuertzService.cs

using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Topshelf;

namespace ConsoleApp1
{
    public class QuartzServer : ServiceControl, ServiceSuspend
    {
        private readonly IScheduler scheduler;

        public QuartzServer()
        {
            scheduler = StdSchedulerFactory.GetDefaultScheduler();
        }

        public bool Start(HostControl hostControl)
        {
            scheduler.Start();
            return true;
        }

        public bool Stop(HostControl hostControl)
        {
            scheduler.Clear();
            return true;
        }

        public bool Continue(HostControl hostControl)
        {
            scheduler.ResumeAll();
            return true;
        }

        public bool Pause(HostControl hostControl)
        {
            scheduler.PauseAll();
            return true;
        }
    }
}

4.新建quartz.config

# You can configure your scheduler in either <quartz> configuration section
# or in quartz properties file
# Configuration section has precedence

quartz.scheduler.instanceName = ServerScheduler

# configure thread pool info
quartz.threadPool.type = Quartz.Simpl.SimpleThreadPool, Quartz
quartz.threadPool.threadCount = 10
quartz.threadPool.threadPriority = Normal

# job initialization plugin handles our xml reading, without it defaults are used
quartz.plugin.xml.type = Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz
quartz.plugin.xml.fileNames = ~/quartz_jobs.xml

# export this server to remoting context
quartz.scheduler.exporter.type = Quartz.Simpl.RemotingSchedulerExporter, Quartz
quartz.scheduler.exporter.port = 555
quartz.scheduler.exporter.bindName = QuartzScheduler
quartz.scheduler.exporter.channelType = tcp
quartz.scheduler.exporter.channelName = httpQuartz

5、新建MyJob.cs 

using CsharpHttpHelper;
using CsharpHttpHelper.Enum;
using Newtonsoft.Json;
using Quartz;

using System;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    /// <summary>
    /// This is just a simple job that says "Hello" to the world.
    /// </summary>
    /// <author>Bill Kratzer</author>
    /// <author>Marko Lahma (.NET)</author>

    public class MyJob : IJob
    {
        //private static readonly ILog log = LogProvider.GetLogger(typeof(HelloJob));

        /// <summary>
        /// Called by the <see cref="IScheduler" /> when a
        /// <see cref="ITrigger" /> fires that is associated with
        /// the <see cref="IJob" />.
        /// </summary>
        public void Execute(IJobExecutionContext context)
        {
           
            string month = DateTime.Now.ToString("yyyy-MM") + "-01";
            

;         
           
           var http = new CsharpHttpHelper.HttpHelper();

            // 创建Httphelper参数对象
            HttpItem item = new HttpItem()
            {
                URL = "http://***.com?month="+month, // URL     必需项
                Method = "post", // URL     可选项 默认为Get
                ContentType = "application/json;charset=utf-8", // 返回类型    可选项有默认值
               // PostDataType = PostDataType.String,
                //PostEncoding = Encoding.UTF8, 
               // Postdata = postdate
            };

            // 请求的返回值对象
            HttpResult result = http.GetHtml(item);
            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                try {
                    if (JsonConvert.DeserializeObject<dynamic>(result.Html).Status == "true")
                        DingTalkHelper.PushDingTalkText(month + "代帐月份自动生成成功!" + result.Html);
                }
                catch (Exception e) {
                    DingTalkHelper.PushDingTalkText(month + "代帐月份自动生成失败!" + result.Html);
                }
            }
            else
            {
                DingTalkHelper.PushDingTalkText(month + "代帐月份自动生成失败!"+result.Html);
            }

        }
    }
}

6、新建quart_jobs.xml

<?xml version="1.0" encoding="UTF-8"?>

<job-scheduling-data xmlns="http://quartznet.sourceforge.net/JobSchedulingData"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 				version="2.0">

  <processing-directives>
    <overwrite-existing-data>true</overwrite-existing-data>
  </processing-directives>

  <schedule>

    <job>
      <name>jobName1</name>
      <group>jobGroup1</group>
      <description>jobDesciption1</description>
      <job-type>ConsoleApp1.MyJob,ConsoleApp1</job-type>
      <durable>true</durable>
      <recover>false</recover>
    </job>

    <trigger>
      <cron>
        <name>UpdateInventoryTrigger</name>
        <group>jobGroup1</group>
        <job-name>jobName1</job-name>
        <job-group>jobGroup1</job-group>
        <start-time>2017-12-01T00:00:00+08:00</start-time>
        <cron-expression>0 0 1 1 * ? *</cron-expression>
      </cron>
    </trigger>

  </schedule>

</job-scheduling-data>

7、修改Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Topshelf;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            HostFactory.Run(x =>
            {
                x.Service<QuartzServer>();
                x.SetDescription("每月1号代帐月份自动生成");
                x.SetDisplayName("代帐月份自动生成");
                x.SetServiceName("DZMonthcreate");
            });
        }
    }
}
9、dingtalk辅助类
using CsharpHttpHelper.Enum;
using CsharpHttpHelper.Item;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ze.Common;

namespace CsharpHttpHelper
{
  public static  class DingTalkHelper
    {
        #region 钉钉dingtalk推送text
        /// <summary>
        /// 钉钉dingtalk推送text xyh 2018-05-18
        /// </summary>
        /// <param name="msg">推送的信息</param>/
        ///  <param name="url">顶顶机器人url</param>
        /// <returns>ResultMessage</returns>
        public static ResultMessage  PushDingTalkText(string msg,string url= "https://oapi.dingtalk.com/robot/send?access_token=****")
        {
            // 要Post的数据
            DingtackModel dk = new DingtackModel();
            dk.text = new Text { content = msg };
            string[] a = { "15158116269" };
            dk.at = new AT(a) { isAtAll = true };
            string postdate = CsharpHttpHelper.HttpHelper.ObjectToJson(dk);

            // 将Post数据转为字节数组
            // byte[] bytedate = System.Text.Encoding.UTF8.GetBytes(postdate);
            CsharpHttpHelper.HttpHelper http = new CsharpHttpHelper.HttpHelper();

            // 创建Httphelper参数对象
            HttpItem item = new HttpItem()
            {
                URL =url, // URL     必需项
                Method = "post", // URL     可选项 默认为Get
                ContentType = "application/json;charset=utf-8", // 返回类型    可选项有默认值
                PostDataType = PostDataType.String,
                PostEncoding = Encoding.UTF8, // 【钉钉】注意,发起POST请求时,必须将字符集编码设置成UTF-8。
                Postdata = postdate
            };

            // 请求的返回值对象
            HttpResult result = http.GetHtml(item);

            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                return new ResultMessage(true, "DingTalk发送成功");
            }
            else
            {
                return new ResultMessage(false, "DingTalk发送失败");
            }
        }
        #endregion
        #region 钉钉dingtalk推送ActionCard
        /// <summary>
        /// 钉钉dingtalk推送ActionCard xyh 2018-05-18
        /// </summary>
        /// <param name="title">首屏会话透出的展示内容</param>
        /// <param name="msg">推送的信息</param>
        /// <param name="singleURL">单个按钮的方案。(设置此项和singleURL后btns无效。)</param>
        /// <param name="url">顶顶机器人url</param>
        /// <returns>ResultMessage</returns>
        public static ResultMessage PushDingTalkActionCard(string title, string msg, string singleURL,string url= "https://oapi.dingtalk.com/robot/send?access_token=****")
        {
            // 要Post的数据
            ActionCardModel ac = new ActionCardModel();
            ac.actionCard = new ActionCard(title, msg, singleURL) { };
            string postdate = CsharpHttpHelper.HttpHelper.ObjectToJson(ac);

            // 将Post数据转为字节数组
            // byte[] bytedate = System.Text.Encoding.UTF8.GetBytes(postdate);
            CsharpHttpHelper.HttpHelper http = new CsharpHttpHelper.HttpHelper();

            // 创建Httphelper参数对象
            HttpItem item = new HttpItem()
            {
                URL = url, // URL     必需项
                Method = "post", // URL     可选项 默认为Get
                ContentType = "application/json;charset=utf-8", // 返回类型    可选项有默认值
                PostDataType = PostDataType.String,
                PostEncoding = Encoding.UTF8, // 【钉钉】注意,发起POST请求时,必须将字符集编码设置成UTF-8。
                Postdata = postdate
            };

            // 请求的返回值对象
            HttpResult result = http.GetHtml(item);

            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                return new ResultMessage(true, "DingTalk发送成功");
            }
            else
            {
                return new ResultMessage(false, "DingTalk发送失败");
            }
        }
        #endregion
    }
}

10.HttpHelper类来自http://www.sufeinet.com/

11.dingtalkModel类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CsharpHttpHelper.Item
{
    class DingTackModel
    {
    }
    public class DingtackModel
    {
        public string msgtype = "text";
        public Text text { get; set; }
        public AT at { get; set; }

    }
    public class AT
    {
        public AT(string[] a)
        {
            atMobiles = a;
        }
        public string[] atMobiles { get; set; }
        public bool isAtAll { get; set; }
    }
    public class Text
    {
        public string content { get; set; }
    }

    public class ActionCardModel
    {
        public ActionCard actionCard { get; set; }
        public string msgtype = "actionCard"; // 此消息类型为固定actionCard

    }
    public class ActionCard
    {
        public ActionCard(string ti, string te, string si)
        {
            title = ti;
            text = te;
            singleURL = si;
        }
        public string title { get; set; } // 首屏会话透出的展示内容
        public string text { get; set; } // markdown格式的消息
        public string hideAvatar = "0"; // 0-正常发消息者头像,1-隐藏发消息者头像
        public string btnOrientation = "0"; // 0-按钮竖直排列,1-按钮横向排列
        public string singleTitle = "阅读全文"; //单个按钮的方案。(设置此项和singleURL后btns无效。)
        public string singleURL { get; set; } // 点击singleTitle按钮触发的URL
    }
}


猜你喜欢

转载自blog.csdn.net/chenjian88886666/article/details/80524883
今日推荐