1、创建一个自动处理中心任务参数的类,直接源码:

namespace Frame.AutoProcess
{
    /// <summary>
    /// 委托(用于异步处理任务)
    /// </summary>
    /// <param name="parameter">任务参数</param>
    /// <returns>是否执行成功</returns>
    public delegate bool TaskHandle(object parameter);

/// <summary>
    /// 自动处理中心任务参数
    /// </summary>
    public class BackgroundTask
    {
        #region 私有成员
        private bool _IsOnce = true; //是否执行一次
        private bool _IsExecuteNow = false; //是否立即执行,对于重复执行生效
        private int _Interval = 86400; //重复执行时的执行间隔,秒为单位,默认为一天,如果只执行一次并且想马上执行将该值设置为0
        private bool _IsAbortExcute = false; //终止执行(设置为true时,系统将不会执行Timer的事件)
        private TaskHandle _ExecuteMethod = null; //任务执行方法
        private object _Parameter = null; //任务执行方法参数
        private DateTime? _ExecuteDateTime = null;
        #endregion

#region 属性

/// <summary>
        /// 是否已经终止
        /// </summary>
        public bool IsAbortExcute
        {
            get { return this._IsAbortExcute; }
        }

/// <summary>
        /// 执行的方法
        /// </summary>
        public TaskHandle ExecuteMethod
        {
            get { return this._ExecuteMethod; }
        }

#endregion

#region 构造函数

/// <summary>
        /// 任务参数构造函数
        /// </summary>
        /// <param name="executeMethod">执行方法</param>
        /// <param name="parameter">方法参数</param>
        /// <param name="isOnce">是否执行一次</param>
        /// <param name="interval">执行间隔(秒),默认为24小时</param>
        /// <param name="isExecuteNow">是否立即执行</param>
        /// <param name="executeDateTime"></param>
        public BackgroundTask(TaskHandle executeMethod, object parameter = null, bool isOnce = true, int interval = 86400, bool isExecuteNow = false, DateTime? executeDateTime = null)
        {
            this._ExecuteMethod = executeMethod;
            this._Parameter = parameter;
            this._IsOnce = isOnce;
            this._Interval = interval;
            if (interval < 0)
            {
                this._Interval = 1;
            }
            this._IsExecuteNow = isExecuteNow;
            this._ExecuteDateTime = executeDateTime;
        }

#endregion

/// <summary>
        /// 开始执行任务
        /// </summary>
        /// <returns></returns>
        public void Execute()
        {
            if (!AutoProcessTask.IsStart) return;
            int interval = _Interval * 1000;
            if (interval == 0) interval = 1;
            /*
             Timer是提供以指定的时间间隔执行某方法的这样一种机制,
             * 即如果想要实现一个定时发送数据,比如每隔3s中发送一次心跳报文,或者执行某个指定的方法,
             * 都可以考虑用Timer类来实现,
             * 不过要提出的是Timer类一边用来做一些比较简单又不耗时间的操作。
             * 据说是因为它执行的任务仍然在主线程里面
             */
            if (this._ExecuteDateTime.HasValue) //按执行时间时每秒跑一次
                interval = 1000;
            Timer _timer = new Timer(interval);
            _timer.AutoReset = !_IsOnce;
            _timer.Enabled = true;
            if (_IsExecuteNow && !_IsOnce) //立即执行
            {
                _ExecuteMethod.BeginInvoke(_Parameter, null, null);
            }
            _timer.Elapsed += new ElapsedEventHandler(Start);
            if (_IsOnce && _timer != null)
            {
                _timer.Enabled = false;
                _timer.Elapsed -= new ElapsedEventHandler(Start);
                _timer = null;
            }
        }

/// <summary>
        /// 开始执行Timer具体方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Start(object sender, ElapsedEventArgs e)
        {
            if (this._ExecuteDateTime.HasValue)
            {
                DateTime now = DateTime.Now;
                DateTime executeTime = this._ExecuteDateTime.Value;
                if (executeTime.Hour == now.Hour && executeTime.Minute == now.Minute && executeTime.Second == now.Second)
                {
                    _ExecuteMethod.BeginInvoke(_Parameter, null, null);
                }
                else
                {
                    (sender as Timer).Interval = 1000;
                }
            }
            else
            {
                _ExecuteMethod.BeginInvoke(_Parameter, null, null);
            }
        }
    }
}

2、定义自动处理任务的任务操作类,直接源码:

namespace Frame.AutoProcess
{
    /// <summary>
    /// 自动处理任务
    /// </summary>
    public class AutoProcessTask
    {
        /// <summary>
        /// 执行Execute方法后事件
        /// </summary>
        public static event EventHandler EventAfterExecute;

/// <summary>
        /// 是否已经开始运行
        /// </summary>
        private static bool isStart = false;

/// <summary>
        /// 任务列表
        /// </summary>
        private static List<BackgroundTask> taskList = new List<BackgroundTask>();

/// <summary>
        /// 是否启动
        /// </summary>
        public static bool IsStart
        {
            get { return isStart; }
        }
       
        /// <summary>
        /// 添加任务
        /// </summary>
        /// <param name="task">任务对象</param>
        public static void AddTask(BackgroundTask task)
        {
            if (task != null && isStart)
            {
                BackgroundTask tempTask = taskList.Where(O => O.ExecuteMethod == task.ExecuteMethod).FirstOrDefault();
                if (tempTask != null) //系统已存在该任务
                {
                    return;
                }
                taskList.Add(task); //添加到任务列表
                task.Execute(); //开始执行任务
            }
        }

/// <summary>
        /// 执行任务
        /// </summary>
        public static void Execute()
        {
            isStart = true;
            if (EventAfterExecute != null)
            {
                EventAfterExecute(null, null);
            }
        }
    }
}

3、调用方式,一般都是在工程启动的时候添加如下直接源码:

BackgroundTask extractAttachmentTextTask = new BackgroundTask((args) =>
            {
                string errMsg = string.Empty;
                try
                {
                   你的逻辑。。。。。。。。。。
                }
                catch
                { }
                return true;
            }, null, false, 3600, false);//每小时执行一次

C#&.Net干货分享-构建后台自动定时任务的源码的更多相关文章

  1. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(2)-easyui构建前端页面框架[附源码]

    原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(2)-easyui构建前端页面框架[附源码] 开始,我们有了一系列的解决方案,我们将动手搭建新系统吧. 用 ...

  2. NhibernateProfiler-写个自动破解工具(源码)

    04 2013 档案   [屌丝的逆袭系列]是个人都能破解之终结NhibernateProfiler-写个自动破解工具(源码) 摘要: 破解思路分析及手动破解 增加“附加到进程”功能--功能介绍增加“ ...

  3. Delphi制作QQ自动登录器源码

    Delphi制作QQ自动登录器源码  http://www.cnblogs.com/sunsoft/archive/2011/02/25/1964967.html 以TM2009为例,检查了一下,未登 ...

  4. C#&.Net干货分享- 构建Spire-Office相关Helper操作Word、Excel、PDF等

    先下载好如下的组件: 直接使用完整源码分享: namespace Frame.Office{    /// <summary>    /// Spire_WordHelper    /// ...

  5. ASP.NET MVC5+EF6+EasyUI 后台管理系统(2)-easyui构建前端页面框架[附源码]

    系列目录 前言 为了符合后面更新后的重构系统,本文于2016-10-31日修正一些截图,文字 我们有了一系列的解决方案,我们将动手搭建新系统吧. 后台系统没有多大的UI视觉,这次我们采用的是标准的左右 ...

  6. 分享非常漂亮的WPF界面框架源码及插件化实现原理

      在上文<分享一个非常漂亮的WPF界面框架>中我简单的介绍了一个界面框架,有朋友已经指出了,这个界面框架是基于ModernUI来实现的,在该文我将分享所有的源码,并详细描述如何基于Mod ...

  7. extjs+MVC4+PetaPoco+AutoFac+AutoMapper后台管理系统(附源码)

    前言 本项目使用的开发环境及技术列举如下:1.开发环境IDE:VS2010+MVC4数据库:SQLServer20082.技术前端:Extjs后端:(1).数据持久层:轻量级ORM框架PetaPoco ...

  8. android完整智能家居、备忘录、蓝牙配对、3D动画库、购物车页面、版本更新自动安装等源码

    Android精选源码 app 版本更新.下载完毕自动自动安装 android指针式分数仪表盘 ANdroid蓝牙设备搜索.配对 Android 图片水印框架,支持隐形数字水印 android3D旋转 ...

  9. 使用Jenkins+Pipline 持构建自动化部署之安卓源码打包、测试、邮件通知

    一.引言 Jenkins 2.x的精髓是Pipeline as Code,那为什么要用Pipeline呢?jenkins1.0也能实现自动化构建,但Pipeline能够将以前project中的配置信息 ...

随机推荐

  1. 阅读webpack代码笔记:antd-layout的webpack.config.prod.js

    'use strict'; const autoprefixer = require('autoprefixer');//自动补全css前缀 const path = require('path'); ...

  2. C++之new关键字

    我们都知道new是用来在程序运行过程中为变量临时分配内存的C++关键字,那它跟C语言中的malloc有什么区别呢,相比之下又为什么推荐使用new呢 c++ throwing() void* opera ...

  3. Python 下JSON的两种编解码方式实例解析

    概念   JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写.在日常的工作中,应用范围极其广泛.这里就介绍python下它的两种编解码方法: ...

  4. MySQL数据库基础笔记

    数据库 数据库就是存储和管理数据的仓库,用户可以对数据库中的数据进行增删改查等操作. 数据库的分类 关系型数据库(Oracle.MySQL.SQLite等) 非关系型数据库(Redis.MongoDB ...

  5. 东芝半导体最新ARM开发板——TT_M3HQ开箱评测

    前言 最近从面包板社区申请到一块东芝最新ARM Cortex-M3内核的开发板--TT_M3HQ,其实开发板收到好几天了,这几天一直在构思怎么来写这第一篇评测文章,看大家在社区也都发了第一篇评测,我也 ...

  6. Linux 周期任务

    一次性任务 在某个特定的时间,执行一次后被清除 相关命令/进程 at 命令 atd进程 在centos6中,系统服务的名称: /etc/init.d/atd 查看系统上该进程时候启动: [root@e ...

  7. js-05-对象(object)

    一.访问对象属性的两种方法 a:objectName.PropertyName     对象名.属性名 b:objectName["PropertyName"]     对象名[“ ...

  8. DOMContentLoaded vs jQuery.ready vs onload, How To Decide When Your Code Should Run

    At a Glance Script tags have access to any element which appears before them in the HTML. jQuery.rea ...

  9. Git 自救指南

    Git 虽然因其分布式管理方式,不完全依赖网络,良好的分支策略,容易部署等优点,已经成为最受欢迎的源代码管理方式.但是一分耕耘一分收获,如果想更好地掌握 git,需要付出大量的学习成本.即使在各种 G ...

  10. Mysql基本注入

    实验环境:墨者学院Mysql手工注入漏洞测试靶场 后台源码没有进行任何字符过滤. 首先进入靶场环境 先用admin登陆试试 果然不行,这时看到用户登录下方有一个停机维护通知,点进去瞅瞅 看到这里链接上 ...