前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >项目实战|C#Socket通讯方式改造(二)--利用Quartz实现定时任务处理

项目实战|C#Socket通讯方式改造(二)--利用Quartz实现定时任务处理

作者头像
Vaccae
发布2020-06-16 16:17:02
6450
发布2020-06-16 16:17:02
举报
文章被收录于专栏:微卡智享微卡智享

学更好的别人,

做更好的自己。

——《微卡智享》

本文长度为3404,预计阅读9分钟

前言

上一篇《项目实战|C#Socket通讯方式改造(一)--Socket实现Ftp的上传和下载》我们简单介绍了项目的背景及需要实现新的方式时利用Socket针对Ftp服务器实现文件的上传和下载,因为方式由原来的实时通讯改为每天的定时通讯,所以我们这篇就来看一下怎么实现定时任务的使用。

项目分析

Quartz实现任务定时处理

微卡智享

其实要实现定时任务处理的方式有比较多的,如直接加一个Timer进行处理,或是做一个Windows服务等,我也是看了一些相关的文章,再做了一下对比后,决定使用Quartz框架的,主要是方便,也快速实现。

实现效果

代码实现

01

创建项目

我们的项目后台用的WebApi所以我们建的这个项目也是WebApi的项目,创建好后基本目录

02

安装Quartz框架

打开管理NuGet程序包,我们搜索Quartz,然后点击安装

因为当时给客户开发的时候用的是.netframework4.5,所以我就装了2.6.2的版本,3.0的版本后需要是.netframework4.5.2以上才可以。

03

生成文件的方法类(TaskDo)

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

namespace QuartzDemo
{
    /// <summary>
    /// 处理做的事
    /// </summary>
    public class TaskDo
    {
        static string filePath = @"D:\IISTest";

        public static void CreateFile()
        {
            Random rd = new Random();
            int count = rd.Next(0, 200);

            //判断路径是否存在,不存在创建
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }

            //将循环完后拼接好的字符串保存到txt文件里,文件名为用户控件名称
            string filename = filePath + "\\file" + count + ".txt";

            StringBuilder sb = new StringBuilder();
            //写入数据
            for (int i = 0; i < count; ++i)
            {
                sb.Append("data:" + i + "|" + DateTime.Now.ToString());
            }
            File.WriteAllText(filename, sb.ToString(), Encoding.UTF8);
        }
    }
}

完成上面的后,我们就开始真正使用Quartz框架了

使用Quartz框架

01

创建任务

创建一个类继承自IJob的接口,然后实现接口中的Execute的方法

using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace QuartzDemo
{
    /// <summary>
    /// 创建QuartzJob的类继承IJOB的接口,在Execute中加入实现方法
    /// </summary>
    public class QuartzJob : IJob
    {
        public void Execute(IJobExecutionContext context)
        {
            //调用TaskDo下面的生成文件方法
            TaskDo.CreateFile();
        }
    }
}

02

创建任务调度类

新建一个任务调度类,用于供外部调用。

using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace QuartzDemo
{
    /// <summary>
    /// 创建任务调度类
    /// </summary>
    public class QuartzJobScheduler
    {
        public static void Start()
        {
            //调度器工厂
            ISchedulerFactory factory = new StdSchedulerFactory();
            //调度器
            IScheduler scheduler = factory.GetScheduler();
            scheduler.GetJobGroupNames();

            //计划任务代码实现
            //1.创建任务,调用QuartzJob的类
            IJobDetail detail = JobBuilder.Create<QuartzJob>().Build();
            IJobDetail detail1 = JobBuilder.Create<ListenIISJob>().Build();

            //2.创建触发器
            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity("Job", "Upload")
                .WithSimpleSchedule(
                t => t.WithIntervalInSeconds(60).RepeatForever())
                .Build();
            ITrigger trigger1 = TriggerBuilder.Create()
                .WithIdentity("IIS", "ListenIIS")
                .WithSimpleSchedule(
                t => t.WithIntervalInMinutes(1).RepeatForever())
                .Build();


            //3.添加任务及触发器至调度中
            scheduler.ScheduleJob(detail, trigger);
            scheduler.ScheduleJob(detail1, trigger1);

            //启动
            scheduler.Start();

        }
    }
}

上面的触发器中WithIntervalInSeconds(60)就是设置的间隔时间60秒,这里可以看一下还有分钟,小时的参数,根据这个可以自己设定。

03

设置IIS启动时注册任务

在Global.asax的Application_Start()中加入

//注册定时任务
            QuartzJobScheduler.Start();

这样我们的任务调用就可以完成了,效果如下

TIPS

IIS网站应用程序池中默认的闲置超时为20分钟,如果20分钟没有任务调用API,那我们做的Quartz任务也会被回收,不再启动,所有我们在Demo中又加了一个开启的任务,每隔多少时间调用一次网站,上图代码已经有了,这里把IIS的Job也列一下

using Quartz;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace QuartzDemo
{
    public class ListenIISJob : IJob
    {
        public void Execute(IJobExecutionContext context)
        {
            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:8080/");
                HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
                string desc = rsp.StatusDescription;
                StringBuilder sb = new StringBuilder();
                sb.Append("request" + DateTime.Now.ToString() + "\r\n");

                string file = @"D:\IISTest\request.txt";
                File.AppendAllText(file, sb.ToString(), Encoding.UTF8);
                
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
}

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-06-15,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 微卡智享 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 实现效果
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档