Quartz公共类,log4net 日志分目录 ,调度任务。
版本:Quartz 2.5 ,log4net 2.0.8
QuartzHelper
namespace Job.Common
{
public class QuartzHelper
{
private static List<IScheduler> _listsche = new List<IScheduler>();
/// <summary>
/// 时间间隔执行任务
/// </summary>
/// <typeparam name="T">任务类,必须实现IJob接口</typeparam>
/// <param name="seconds">时间间隔(单位:毫秒)</param>
public static void ExecuteInterval<T>(int seconds) where T : IJob
{
ISchedulerFactory factory = new StdSchedulerFactory();
IScheduler scheduler = factory.GetScheduler(); //IJobDetail job = JobBuilder.Create<T>().WithIdentity("job1", "group1").Build();
IJobDetail job = JobBuilder.Create<T>().Build(); ITrigger trigger = TriggerBuilder.Create()
.StartNow()
.WithSimpleSchedule(x => x.WithIntervalInSeconds(seconds).RepeatForever())
.Build(); _listsche.Add(scheduler);
scheduler.ScheduleJob(job, trigger);
scheduler.Start(); } /// <summary>
/// 指定时间执行任务
/// </summary>
/// <typeparam name="T">任务类,必须实现IJob接口</typeparam>
/// <param name="cronExpression">cron表达式,即指定时间点的表达式</param>
public static void ExecuteByCron<T>(string cronExpression) where T : IJob
{
ISchedulerFactory factory = new StdSchedulerFactory();
IScheduler scheduler = factory.GetScheduler(); IJobDetail job = JobBuilder.Create<T>().Build(); //DateTimeOffset startTime = DateBuilder.NextGivenSecondDate(DateTime.Now.AddSeconds(1), 2);
//DateTimeOffset endTime = DateBuilder.NextGivenSecondDate(DateTime.Now.AddYears(2), 3); ICronTrigger trigger = (ICronTrigger)TriggerBuilder.Create()
// .StartAt(startTime).EndAt(endTime)
.WithCronSchedule(cronExpression)
.StartNow()
.Build(); _listsche.Add(scheduler);
scheduler.ScheduleJob(job, trigger);
scheduler.Start(); //Thread.Sleep(TimeSpan.FromDays(2));
//scheduler.Shutdown();
} /// <summary>
/// 每隔 seconds秒 ,重复执行times次 (如:times=-1重复执行;times=0只执行一次;
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="seconds"></param>
/// <param name="times"></param>
public static void ExecuteIntervalTime<T>(int seconds, int times) where T : IJob
{
ISchedulerFactory factory = new StdSchedulerFactory();
IScheduler scheduler = factory.GetScheduler();
//IJobDetail job = JobBuilder.Create<T>().WithIdentity("job1", "group1").Build();
IJobDetail job = JobBuilder.Create<T>().Build(); ITrigger trigger = TriggerBuilder.Create()
.StartNow()
.WithSimpleSchedule(x => x.WithIntervalInSeconds(seconds).WithRepeatCount(times))
.Build(); _listsche.Add(scheduler);
scheduler.ScheduleJob(job, trigger);
scheduler.Start();
} /// <summary>
/// 关闭所有工厂调度任务
/// </summary>
public static void ShutdownJobs()
{
try
{
if (_listsche.Count > )
{
foreach (var sched in _listsche)
{
if (!sched.IsShutdown)
{
logclass.Info(string.Format("关闭任务调度:{0}", sched.SchedulerName));
sched.Shutdown();
}
}
_listsche.Clear();
}
}
catch (Exception e)
{
logclass.Error(string.Format("关闭任务调度,出错:{0}", e), e);
}
} } public class QuartzManager<T> where T : class,IJob
{
#region 变量
private static ISchedulerFactory schedulerFactory = new StdSchedulerFactory(); //scheduler工厂
private static String JOB_GROUP_NAME = "JOBGROUP_NAME"; //Job群组名
private static String TRIGGER_GROUP_NAME = "TRIGGERGROUP_NAME"; //触发器群组名
#endregion #region 添加,删除,修改Job方法
/// <summary>
/// 添加一个定时任务,使用默认的任务组名,触发器名,触发器组名
/// </summary>
/// <param name="pStrJobName">任务名</param>
/// <param name="pStrCronExpress">触发器表达式</param>
public static void addJob(string pStrJobName, string pStrCronExpress, IDictionary<string, object> pDictionary)
{
try
{
IScheduler sched = schedulerFactory.GetScheduler();
// 创建任务
IJobDetail job = JobBuilder.Create<T>()
.WithIdentity(pStrJobName, JOB_GROUP_NAME)
.Build(); // 创建触发器
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity(pStrJobName, TRIGGER_GROUP_NAME)
.WithCronSchedule(pStrCronExpress)
.Build(); //给任务传参数
foreach (KeyValuePair<string, object> kvp in pDictionary)
{
job.JobDataMap.Put(kvp.Key, kvp.Value);
} sched.ScheduleJob(job, trigger);
}
catch (Exception e)
{
throw new Exception(e.Message);
}
} /// <summary>
/// 移除一个任务(使用默认的任务组名,触发器名,触发器组名)
/// </summary>
/// <param name="pStrJobName">任务名称</param>
public static void RemoveJob(string pStrJobName)
{
try
{
IScheduler sched = schedulerFactory.GetScheduler();
JobKey jobKey = new JobKey(pStrJobName);
TriggerKey triggerKey = new TriggerKey(pStrJobName, TRIGGER_GROUP_NAME);
sched.PauseTrigger(triggerKey);// 停止触发器
sched.UnscheduleJob(triggerKey);// 移除触发器
sched.DeleteJob(jobKey);// 删除任务
}
catch (Exception e)
{
throw new Exception(e.Message);
}
} /// <summary>
/// 修改一个任务的触发时间(使用默认的任务组名,触发器名,触发器组名)
/// </summary>
/// <param name="pStrJobName">任务名</param>
/// <param name="pStrCronExpress">触发器表达式</param>
public static void ModifyJobTime(string pStrJobName, string pStrCronExpress, IDictionary<string, object> pDictionary)
{
try
{
IScheduler sched = schedulerFactory.GetScheduler();
TriggerKey triggerKey = new TriggerKey(pStrJobName, TRIGGER_GROUP_NAME);
ICronTrigger trigger = (ICronTrigger)sched.GetTrigger(triggerKey);
if (trigger == null)
{
return;
}
RemoveJob(pStrJobName);
addJob(pStrJobName, pStrCronExpress, pDictionary);
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
#endregion #region 启动,关闭Job
/// <summary>
/// 启动所有定时任务
/// </summary>
public static void startJobs()
{
try
{
IScheduler sched = schedulerFactory.GetScheduler();
sched.Start();
}
catch (Exception e)
{
throw new Exception(e.Message);
}
} /// <summary>
/// 关闭所有定时任务
/// </summary>
public static void ShutdownJobs()
{
try
{
IScheduler sched = schedulerFactory.GetScheduler();
if (!sched.IsShutdown)
{
sched.Shutdown();
}
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
#endregion } }
Loghelper
namespace Job.Common
{
/// <summary>
/// 动态创建Logger工厂类
/// </summary>
public static class LogHelper
{
private static readonly ConcurrentDictionary<string, ILog> loggerContainer = new ConcurrentDictionary<string, ILog>(); private static readonly Dictionary<string, ReadParamAppender> appenderContainer = new Dictionary<string, ReadParamAppender>();
private static object lockObj = new object(); //默认配置
private const int MAX_SIZE_ROLL_BACKUPS = ;
private const string LAYOUT_PATTERN = "%d [%t] %-5p %c - %m%n";
private const string DATE_PATTERN = "yyyyMMdd/HH\".log\"";
private const string MAXIMUM_FILE_SIZE = "256MB";
private const string LEVEL = "debug"; //读取配置文件并缓存
static LogHelper()
{
IAppender[] appenders = LogManager.GetRepository().GetAppenders();
for (int i = ; i < appenders.Length; i++)
{
if (appenders[i] is ReadParamAppender)
{
ReadParamAppender appender = (ReadParamAppender)appenders[i];
if (appender.MaxSizeRollBackups == )
{
appender.MaxSizeRollBackups = MAX_SIZE_ROLL_BACKUPS;
}
if (appender.Layout != null && appender.Layout is log4net.Layout.PatternLayout)
{
appender.LayoutPattern = ((log4net.Layout.PatternLayout)appender.Layout).ConversionPattern;
}
if (string.IsNullOrEmpty(appender.LayoutPattern))
{
appender.LayoutPattern = LAYOUT_PATTERN;
}
if (string.IsNullOrEmpty(appender.DatePattern))
{
appender.DatePattern = DATE_PATTERN;
}
if (string.IsNullOrEmpty(appender.MaximumFileSize))
{
appender.MaximumFileSize = MAXIMUM_FILE_SIZE;
}
if (string.IsNullOrEmpty(appender.Level))
{
appender.Level = LEVEL;
}
lock (lockObj)
{
appenderContainer[appenders[i].Name] = appender;
}
}
}
} /// <summary>
/// 文本日志
/// </summary>
/// <param name="loggerName"></param>
/// <returns></returns>
public static ILog GetCustomLogger(string loggerName, string category = null, bool additivity = false)
{
return loggerContainer.GetOrAdd(loggerName, delegate(string name)
{
RollingFileAppender newAppender = null;
ReadParamAppender appender = null;
if (appenderContainer.ContainsKey(loggerName))
{
appender = appenderContainer[loggerName];
newAppender = GetNewFileApender(loggerName, string.IsNullOrEmpty(appender.File) ? GetFile(category, loggerName) : appender.File, appender.MaxSizeRollBackups,
appender.AppendToFile, true, appender.MaximumFileSize, RollingFileAppender.RollingMode.Composite, appender.DatePattern, appender.LayoutPattern);
}
else
{
newAppender = GetNewFileApender(loggerName, GetFile(category, loggerName), MAX_SIZE_ROLL_BACKUPS, true, false, MAXIMUM_FILE_SIZE, RollingFileAppender.RollingMode.Date,
DATE_PATTERN, LAYOUT_PATTERN);
}
log4net.Repository.Hierarchy.Hierarchy repository = (log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository();
Logger logger = repository.LoggerFactory.CreateLogger(repository, loggerName);
logger.Hierarchy = repository;
logger.Parent = repository.Root;
logger.Level = GetLoggerLevel(appender == null ? LEVEL : appender.Level);
logger.Additivity = additivity;
logger.AddAppender(newAppender);
logger.Repository.Configured = true;
return new LogImpl(logger);
});
} //如果没有指定文件路径则在运行路径下建立 Log\{loggerName}.txt private static string GetFile(string category, string loggerName)
{
if (string.IsNullOrEmpty(category))
{
return string.Format(@"Log\{0}\", loggerName);
}
else
{
return string.Format(@"Log\{0}\{1}\", category, loggerName);
}
} private static Level GetLoggerLevel(string level)
{
if (!string.IsNullOrEmpty(level))
{
switch (level.ToLower().Trim())
{
case "debug":
return Level.Debug; case "info":
return Level.Info; case "warn":
return Level.Warn; case "error":
return Level.Error; case "fatal":
return Level.Fatal;
}
}
return Level.Debug;
} private static RollingFileAppender GetNewFileApender(string appenderName, string file, int maxSizeRollBackups, bool appendToFile = true, bool staticLogFileName = false, string maximumFileSize = "50MB", RollingFileAppender.RollingMode rollingMode = RollingFileAppender.RollingMode.Date, string datePattern = "yyyyMMdd\".log\"", string layoutPattern = "%d [%t] %-5p %c - %m%n")
{
RollingFileAppender appender = new RollingFileAppender
{
LockingModel = new FileAppender.MinimalLock(),
Name = appenderName,
File = file,
AppendToFile = appendToFile,
MaxSizeRollBackups = maxSizeRollBackups,
MaximumFileSize = maximumFileSize,
StaticLogFileName = staticLogFileName,
RollingStyle = rollingMode,
DatePattern = datePattern,
};
PatternLayout layout = new PatternLayout(layoutPattern);
appender.Layout = layout;
layout.ActivateOptions();
appender.ActivateOptions();
return appender;
}
}
/// <summary>
/// 自定义读取配置文件的Appender
/// </summary>
public class ReadParamAppender : log4net.Appender.AppenderSkeleton
{
private string _file;
public string File
{
get { return this._file; }
set { _file = value; }
} private int _maxSizeRollBackups;
public int MaxSizeRollBackups
{
get { return this._maxSizeRollBackups; }
set { _maxSizeRollBackups = value; }
} private bool _appendToFile = true;
public bool AppendToFile
{
get { return this._appendToFile; }
set { _appendToFile = value; }
} private string _maximumFileSize;
public string MaximumFileSize
{
get { return this._maximumFileSize; }
set { _maximumFileSize = value; }
} private string _layoutPattern;
public string LayoutPattern
{
get { return this._layoutPattern; }
set { _layoutPattern = value; }
} private string _datePattern;
public string DatePattern
{
get { return this._datePattern; }
set { _datePattern = value; }
} private string _level;
public string Level
{
get { return this._level; }
set { _level = value; }
} protected override void Append(log4net.Core.LoggingEvent loggingEvent)
{
}
} }
Quartz公共类,log4net 日志分目录 ,调度任务。的更多相关文章
- 【Java EE 学习 77 上】【数据采集系统第九天】【通过AOP实现日志管理】【通过Spring石英调度动态生成日志表】【日志分表和查询】
一.需求分析 日志数据在很多行业中都是非常敏感的数据,它们不能删除只能保存和查看,这样日志表就会越来越大,我们不可能永远让它无限制的增长下去,必须采取一种手段将数据分散开来.假设现在整个数据库需要保存 ...
- Log4net日志使用教程-控制台、文本、数据库三种记录方式
一.log4net简介: 1. Log4net的优点: 几乎所有的大型应用都会有自己的用于跟踪调试的API.因为一旦程序被部署以后,就不太可能再利用专门的调试工具了.然而一个管理员可能需要有一套强大的 ...
- 使用log4net日志组件经验分享
常见步骤: 第一:在项目中引用log4net组件. 第二:配置log4net,一般都写在web.config中. 第三:调用部分. 具体怎么配置,大家可以参考博客其它博友写的,这里我只写我 ...
- 第一节:框架前期准备篇之Log4Net日志详解
一. Log4Net简介 Log4net是从Java中的Log4j迁移过来的一个.Net版的开源日志框架,它的功能很强大,可以将日志分为不同的等级,以不同的格式输出到不同的存储介质中,比如:数据库.t ...
- log4net日志组件经验分享
引自log4net日志组件经验分享 我们在开发WEB项目的时候,经常会出现这样的情况:在本地调试都是正常的,但是部署到服务器上就不行了.一般出现这种情况很大一部分原因是因为服务的环境和本地不同,数据库 ...
- Log4net 日志使用介绍
概述 Log4net 有三个主要组件:loggers,appenders 和 layouts.这三个组件一起工作使得开发者能够根据信息类型和等级(Level)记录信息,以及在运行时控制信息的格式化和信 ...
- log4net日志组件
转载:http://www.cnblogs.com/knowledgesea/archive/2012/04/26/2471414.html 一.什么是log4net组件 Log4net是基于.net ...
- C#Log4net日志记录组件的使用
一.Log4Net介绍 Log4net是基于.NET开发的一款非常著名的记录日志开源组件.它通过一套XML配置的日志引擎,将日志分不同的等级,分别是:FATAL . ERROR. WARN. INFO ...
- Log4net 日志
Log4net 日志使用介绍 概述 Log4net 有三个主要组件:loggers,appenders 和 layouts.这三个组件一起工作使得开发者能够根据信息类型和等级(Level)记录信息,以 ...
随机推荐
- elasticsearch 的内存JVM和GC相关问题
JVM对ElasticSearch集群的稳定性有很大的影响. Java是一个垃圾收集语言,意思是这个程序不会手动管理分配和释放内存.程序员只需要编写代码,jvm管理根据需要管理分配内存的处理,然后在不 ...
- Ubuntu的显示问题不全解决
首先我们安装的是Ubuntu 16.04版本.最开始一直不能解分辨率问题,导致信息显示不全 利用xrandr -s 1369x768(中间x是乘号不是英文字母) 命令来设置分辨率, 需注意的是: 1. ...
- Python 语法1
函数的定义: """ def 函数名(): 函数内容,函数内容, 函数内容,函数内容, """ ////////////////////// ...
- JS查看对象属性的方式
var person = { type: 'person', say: function(){ console.log("Hellow World!") } } //以person ...
- golang context
ex1 package main import ( "fmt" ) // 最佳context 实践 // Context 目标是实现各个goroutine能及时终止退出. func ...
- token简单的使用
这里对token的简单的使用进行测试和描述 其原理就不在这里描述了! 具体测试流程:用户在前端请求登录——>在后台验证通过后根据用户ID生成token——>请求返回时将token带给前端并 ...
- 多个DispatcherServlet有什么用处.md
有看到一些应用在 web.xml 文件中配置了多个 DispatcherServlet,例如: <servlet> <servlet-name>en</servle ...
- mysql 唯一索引与null.md
mysql 的唯一索引要求所有参与的列都不能够为 null 值,如果唯一索引中的任何一个元素含有 null 值,则唯一约束将不起作用. 示例代码 create table tb ( a int, b ...
- centos7 - mongodb3.6.5-配置文件
创建Linux管理员账号admin, 并加入wheel组,对mongodb, php等进行统一管理~ systemLog:destination: filelogAppend: truepath: / ...
- Hadoop学习笔记1 - 使用Java API访问远程hdfs集群
转载请标注原链接 http://www.cnblogs.com/xczyd/p/8570437.html 2018年3月从新司重新起航了.之前在某司过了的蛋疼三个月,也算给自己放了个小假了. 第一个小 ...