在我们平时项目中经常会遇到定时任务,比如定时同步数据,定时备份数据,定时统计数据等,定时任务我们都知道使用Quartz.net,此系列写的也是Quartz,但是在此之前,我们先用其他方式做个简单的定时任务进行入门。

首先呢,我们现在自己先写一个简单的定时循环任务,话不多说,直接上代码:

第一步:创建项目,新建一个类库:我们命名为TaskBase

第二部:添加一个抽象基础类BaseMonitor:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace TaskBase
{
/// <summary>
/// 监测基础抽象类
/// </summary>
public abstract class BaseMonitor
{ protected System.Threading.Thread _thread;
/// <summary>
/// 监控时间间隔(毫秒)
/// </summary>
public virtual int Interval { get; set; } public virtual string Name { get; set; }
/// <summary>
/// 监控器状态
/// </summary>
public virtual TaskState State { get; set; }
public BaseMonitor(string name)
{
Name = name;
_thread = new System.Threading.Thread(BaseRun);
_thread.IsBackground = true;//获取或设置一个值,该值指示某个线程是否为后台线程
_thread.Start();
State = TaskState.运行;
}
private void BaseRun()
{
while (State==TaskState.运行)
{
try
{
Run();
System.Threading.Thread.Sleep(Interval);
}
catch (Exception ex)
{
State = TaskState.异常;
PCore.Log.LogTextHelper.WriteErrorLog(this.GetType().Name + "监控出现错误,此监视器已暂停!", ex);
}
}
}
protected virtual void Run()
{ }
}
}

(代码中PCore.Log.LogTextHelper.WriteErrorLog 是一个写文本日志的方法,可自行写个此方法。)

注:此定时任务基础类 是用 System.Threading.Thread 实现,其中 TaskState为一个枚举来表示任务的状态:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace TaskBase
{
public enum TaskState
{
未开始=,
运行=,
暂停=,
异常=
}
}

第三部:添加一个继承BaseMonitor的TestMontior类,代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace TaskBase
{
public class TestMontior:BaseMonitor
{
/// <summary>
/// 构造函数
/// </summary>
/// <param name="name">检测器名称</param>
public TestMontior(string name) : base(name)
{
}
/// <summary>
/// 监控时间间隔(毫秒)
/// </summary>
public override int Interval
{
get
{
return GlobalConfig.TestMonitorInterval;
}
}
public override string Name
{
get
{
return base.Name;
} set
{
base.Name = value;
}
} public override TaskState State
{
get
{
return base.State;
} set
{
base.State = value;
}
}
protected override void Run()
{
PCore.Log.LogTextHelper.WriteLog("TestMontitor监测器正在监测");
}
}
}

注:TestMontior 相当于我们的Job,代码中 GlobalConfig是我定义的一个全局参数类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace TaskBase
{
public static class GlobalConfig
{
public static int TestMonitorInterval
{
get { return * ; }
} public static List<BaseMonitor> Monitor = new List<BaseMonitor>();
}
}

创建完成之后就是这个样子:

定时任务的基础类库已经创建完毕,下面我们来看怎么使用它。

第四部:在WEB中使用:创建一个WEB  MVC项目,引用TaskBase,然后在Global.asax中添加以下代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing; namespace WebTaskTest
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles); TaskBase.GlobalConfig.Monitor.Add(new TaskBase.TestMontior("测试监控器Test"));//注册定时任务 }
}
}

运行WEB站点,查看日志如下:

可以看到一秒钟执行一次 ,因为我们在GlobalConfig.TestMonitorInterval设置的就是一秒钟。

下面我们看如何在windows server中如何使用:

创建一个WindowsServerTest类库,引用TaskBse,添加一个windows服务:

using Quartz;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks; namespace WindowsServerTest
{
partial class TestService : ServiceBase
{
public TestService()
{
InitializeComponent();
} protected override void OnStart(string[] args)
{
try
{
// TODO: 在此处添加代码以启动服务。
PCore.Log.LogTextHelper.WriteLog("OnStart:Test服务开始..."); TaskBase.GlobalConfig.Monitor.Add(new TaskBase.TestMontior("测试监控器Test"));//注册监视器 }
catch (Exception ex)
{
PCore.Log.LogTextHelper.WriteErrorLog("出错了",ex);
}
} protected override void OnStop()
{ // TODO: 在此处添加代码以执行停止服务所需的关闭操作。
PCore.Log.LogTextHelper.WriteLog("OnStop:Test服务结束...");
}
protected override void OnPause()
{
PCore.Log.LogTextHelper.WriteLog("OnPause:Test服务暂停...");
}
protected override void OnContinue()
{
PCore.Log.LogTextHelper.WriteLog("OnContinue:Test服务继续...");
}
}
}

关于windows服务的安装卸载可自行百度,再此不多哔哔了。

安装好服务开始后,我们查看下日志如下:

此节中我们简单做了一个定时任务,下章我们将进行Quartz.net任务框架的介绍。(源代码会跟随后面的例子一并上传),请继续关注以后章节。

.NET 任务调度Quartz系列(1)——自建定时任务的更多相关文章

  1. spring 任务调度quartz

    简单记录一下spring任务调度quartz的例子 首先添加包 quartz-2.2.3.jar 然后写个简单的TestJob类 package com.job; import java.util.D ...

  2. c/c++ 模板与STL小例子系列<一 >自建Array数组

    c/c++ 模板与STL小例子系列 自建Array数组 自建的Array数组,提供如下对外接口 方法 功能描述 Array() 无参数构造方法,构造元素个数为模板参数个的数组 Array(int le ...

  3. Storm编程入门API系列之Storm的定时任务实现

    概念,见博客 Storm概念学习系列之storm的定时任务 Storm的定时任务,分为两种实现方式,都是可以达到目的的. 我这里,分为StormTopologyTimer1.java   和  Sto ...

  4. Storm概念学习系列之storm的定时任务

    不多说,直接上干货! 至于为什么,有storm的定时任务.这个很简单.但是,这个在工作中非常重要! 假设有如下的业务场景 这个spoult源源不断地发送数据,boilt呢会进行处理.然后呢,处理后的结 ...

  5. 【优化技术专题】「温故而知新」基于Quartz系列的任务调度框架的动态化任务实现分析

    不提XXLJOB或者其他的调度框架,就看我接触的第一个任务调度框架Quartz(温故而知新) Quartz的动态暂停 恢复 修改和删除任务 实现动态添加定时任务,先来看一下我们初步要实现的目标效果图, ...

  6. 定时组件quartz系列<三>quartz调度机制调研及源码分析

    quartz2.2.1集群调度机制调研及源码分析引言quartz集群架构调度器实例化调度过程触发器的获取触发trigger:Job执行过程:总结:附: 引言 quratz是目前最为成熟,使用最广泛的j ...

  7. 定时组件quartz系列<一>模拟定时组件小程序

    一.核心概念 Quartz的原理不是很复杂,只要搞明白几个概念,然后知道如何去启动和关闭一个调度程序即可. 1.Job表示一个工作,要执行的具体内容.此接口中只有一个方法void execute(Jo ...

  8. 任务调度 QUARTZ

    任务调度在目前的JAVA应用程序中运用的十分普遍,故掌握QUARTZ是必备的技能 闲话少说,上官网:http://www.quartz-scheduler.org/ 下载最新1.80资源包 commo ...

  9. 分布式任务调度——quartz + spring + 数据库

        项目中使用分布式并发部署定时任务,多台跨JVM,按照常理逻辑每个JVM的定时任务会各自运行,这样就会存在问题,多台分布式JVM机器的应用服务同时干活,一个是加重服务负担,另外一个是存在严重的逻 ...

随机推荐

  1. 浅谈python中的“ ==” 与“ is”

    在python中,== 与 is 之间既有区别,又有联系,本文将通过实际代码的演示,力争能够帮助读到这篇文章的朋友以最短的时间理清二者的关系,并深刻理解它们在内存中的实现机制.扯淡的话不多说,下面马上 ...

  2. Django的models操作

    一.先看单表操作 增 方式1: models.book.objects.create( Book_name = "aaa", Book_info = "bbb" ...

  3. iOS - OC - JSON 解析 - NSJSONSerialization

    #import "ViewController.h" @interface ViewController () @end @implementation ViewControlle ...

  4. springMVC将处理的后的数据通过post方法传给页面时,可能会出现乱码问题,下面提出解决post乱码问题的方法

    在web.xml中加入: <!-- 解决post乱码问题 --> <filter> <filter-name>CharacterEncodingFilter< ...

  5. JTemplate学习(二)

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DT ...

  6. .NET资源文件实现多语言切换

    1.创建对应的资源文件 lang.en.resx  英文 lang.resx   中文,默认 lang.zh-tw.resx  繁体 首先说明,这三个文件前面部分名称需要一样,只是 点 后面的语言代号 ...

  7. mysql contact_ws函数 字符串被截断问题

    contact函数默认有字符串长度限制,解决方法:SET group_concat_max_len = 20000这个参数设置一下就好了

  8. PAT 1079 延迟的回文数(代码+思路)

    1079 延迟的回文数(20 分) 给定一个 k+1 位的正整数 N,写成 a​k​​⋯a​1​​a​0​​ 的形式,其中对所有 i 有 0≤a​i​​<10 且 a​k​​>0.N 被称 ...

  9. Git 初始状操作指引

    You have an empty repository To get started you will need to run these commands in your terminal. Ne ...

  10. 2018.08.28 洛谷P3345 [ZJOI2015]幻想乡战略游戏(点分树)

    传送门 题目就是要求维护带权重心. 因此破题的关键点自然就是带权重心的性质. 这时发现直接找带权重心是O(n)的,考虑优化方案. 发现点分树的树高是logn级别的,并且对于以u为根的树,带权重心要么就 ...