在上一篇绪中,已经介绍了整个项目的情况下了,接下来就是开始一步步做起来了。
首先:先整个我们的Job任务表,以及Job执行日志表。SQL如下:
drop table if exists job_info;
create table job_info
(
id int not null AUTO_INCREMENT comment '主键',
job_name varchar(150) null default null comment '任务名称',
job_assembly varchar(200) null default null comment '执行的方式的dll名称',
job_class varchar(300) null default null comment '执行的方法类',
job_corn varchar(100) null default null comment '执行任务的corn表达式',
job_type int not null default 1 comment '任务类型,默认为1 简单,2 复杂',
job_execount int null default 0 comment '任务的执行总次数,0表示无限次',
job_starttime datetime null default null comment '任务开始时间',
job_state int null default 0 comment '任务的状态 0 准备中,1 执行中,2 暂定,3 停止,4 结束',
addtime TIMESTAMP null default CURRENT_TIMESTAMP comment '任务的创建时间',
PRIMARY KEY (`id`)
);
drop table if exists job_log;
create table job_log
(
id int not null AUTO_INCREMENT comment '主键',
job_name varchar(150) null default null comment '任务名称',
job_result varchar(200) null default null comment '执行的结果',
job_exception text null default null comment '执行任务的异常信息',
job_exetime int not null default 0 comment '执行耗时,单位ms',
job_exedate datetime null default 0 comment '任务的执行的日期时间',
job_exestate int null default 0 comment '执行结果 0 正常,1 异常',
addtime TIMESTAMP null default CURRENT_TIMESTAMP comment '任务的执行时间',
PRIMARY KEY (`id`)
);
相关实体类与操作方法,如下:
/// <summary>
/// Job信息表
/// </summary>
public class Job_Info : BaseEntity
{
private int _id = ;
private string _job_name;
private string _job_assembly;
private string _job_class;
private string _job_corn;
private int _job_type = ;
private int _job_execount = ;
private DateTime _job_starttime;
private int _job_state = ;
private DateTime _addtime; /// <summary>
/// 主键
/// </summary>
public int Id { get => _id; set => _id = value; }
/// <summary>
/// 任务名称
/// </summary>
public string Job_name { get => _job_name; set => _job_name = value; }
/// <summary>
/// 执行的方式的dll名称
/// </summary>
public string Job_assembly { get => _job_assembly; set => _job_assembly = value; }
/// <summary>
/// 执行的方法类
/// </summary>
public string Job_class { get => _job_class; set => _job_class = value; }
/// <summary>
/// 执行任务的corn表达式
/// </summary>
public string Job_corn { get => _job_corn; set => _job_corn = value; }
/// <summary>
/// 任务类型,默认为1 简单,2 复杂
/// </summary>
public int Job_type { get => _job_type; set => _job_type = value; }
/// <summary>
/// 任务的执行总次数,0表示无限次
/// </summary>
public int Job_execount { get => _job_execount; set => _job_execount = value; }
/// <summary>
/// 任务开始时间
/// </summary>
public DateTime Job_starttime { get => _job_starttime; set => _job_starttime = value; }
/// <summary>
/// 任务的状态 0 准备中,1 执行中,2 暂定,3 停止,4 结束
/// </summary>
public int Job_state { get => _job_state; set => _job_state = value; }
/// <summary>
/// 任务的创建时间
/// </summary>
public DateTime Addtime { get => _addtime; set => _addtime = value; } }
/// <summary>
/// Job运行日志表
/// </summary>
public class Job_Log : BaseEntity
{
private int _id = ;
private string _job_name;
private string _job_result;
private string _job_exception;
private int _job_exetime;
private DateTime _job_exedate;
private int _job_exestate;
private DateTime _addtime; /// <summary>
/// 主键
/// </summary>
public int Id { get => _id; set => _id = value; }
/// <summary>
/// 任务名称
/// </summary>
public string Job_name { get => _job_name; set => _job_name = value; }
/// <summary>
/// 执行的结果
/// </summary>
public string Job_result { get => _job_result; set => _job_result = value; }
/// <summary>
/// 执行任务的异常信息
/// </summary>
public string Job_exception { get => _job_exception; set => _job_exception = value; }
/// <summary>
/// 执行耗时,单位ms
/// </summary>
public int Job_exetime { get => _job_exetime; set => _job_exetime = value; }
/// <summary>
/// 任务的执行的日期时间
/// </summary>
public DateTime Job_exedate { get => _job_exedate; set => _job_exedate = value; }
/// <summary>
/// 执行结果 0 正常,1 异常
/// </summary>
public int Job_exestate { get => _job_exestate; set => _job_exestate = value; }
/// <summary>
/// 任务的执行时间
/// </summary>
public DateTime Addtime { get => _addtime; set => _addtime = value; }
}
/// <summary>
/// Job信息逻辑类
/// </summary>
public class JobInfoBLL
{
/// <summary>
/// 添加Job信息
/// </summary>
/// <param name="jobInfo"></param>
/// <returns></returns>
public int AddInfo(Job_Info jobInfo)
{
int result = ; if (jobInfo == null)
return result;
try
{
string SqlStr = string.Format("insert into job_info(job_name,job_assembly,job_class,job_corn,job_type,job_execount,job_starttime,job_state) values('{0}','{1}','{7}','{2}',{3},{4},'{5}',{6})",
jobInfo.Job_name, jobInfo.Job_assembly, jobInfo.Job_corn, jobInfo.Job_type, jobInfo.Job_execount, jobInfo.Job_starttime.ToString("yyyy-MM-dd HH:mm:ss"), , jobInfo.Job_class);
result = MySqlHelper.ExceuteSql(SqlStr);
}
finally
{ } return result;
} /// <summary>
/// 更新Job的状态
/// </summary>
/// <param name="jobInfo"></param>
/// <returns></returns>
public int UpdateJobState(Job_Info jobInfo)
{
int result = ; if (jobInfo == null)
return result;
try
{
string SqlStr = string.Format("update job_info set job_state={0} where ", jobInfo.Job_state);
if(jobInfo.Id > )
{
SqlStr += string.Format(" id={0};", jobInfo.Id);
}else if (!string.IsNullOrEmpty(jobInfo.Job_name))
{
SqlStr += string.Format(" job_name='{0}'", jobInfo.Job_name);
}
result = MySqlHelper.ExceuteSql(SqlStr);
}
finally
{ } return result;
} /// <summary>
/// job列表
/// </summary>
/// <returns></returns>
public List<Job_Info> GetJobList()
{
List<Job_Info> list = null; try
{
string SqlStr = "select * from job_info";
var ds = MySqlHelper.GetDataSet(SqlStr);
if(ds != null && ds.Tables.Count > && ds.Tables[].Rows.Count > )
{
list = new List<Job_Info>();
Job_Info info = new Job_Info();
foreach (System.Data.DataRow row in ds.Tables[].Rows)
{
info = Job_Info.ToEntity<Job_Info>(row, info);
if (info != null)
list.Add(info);
}
}
}
finally
{ } return list;
} /// <summary>
/// job列表
/// </summary>
/// <returns></returns>
public List<Job_Info> GetJobList(int pageIndex,int pageSize)
{
List<Job_Info> list = null; try
{
string SqlStr = "select * from job_info";
SqlStr += string.Format(" limit {0},{1};", (pageIndex - ) * pageSize, pageSize);
var ds = MySqlHelper.GetDataSet(SqlStr);
if (ds != null && ds.Tables.Count > && ds.Tables[].Rows.Count > )
{
list = new List<Job_Info>();
Job_Info info = new Job_Info();
foreach (System.Data.DataRow row in ds.Tables[].Rows)
{
info = Job_Info.ToEntity<Job_Info>(row, info);
if (info != null)
list.Add(info);
}
}
}
finally
{ } return list;
} public Job_Info GetOne(int id)
{
Job_Info job = null; try
{
string SqlStr = "select * from job_info where id="+id;
var ds = MySqlHelper.GetDataSet(SqlStr);
if (ds != null && ds.Tables.Count > && ds.Tables[].Rows.Count > )
{
job = new Job_Info();
foreach (System.Data.DataRow row in ds.Tables[].Rows)
{
job = Job_Info.ToEntity<Job_Info>(row, job);
}
}
}
catch (Exception ex)
{ } return job;
} /// <summary>
/// job数量
/// </summary>
/// <returns></returns>
public int GetJobCount()
{
int list = ; try
{
string SqlStr = "select count(0) from job_log";
var ds = MySqlHelper.GetReader(SqlStr);
if (ds != null)
{
int.TryParse(ds.ToString(), out list);
}
}
finally
{ } return list;
} }
/// <summary>
/// Job 日志逻辑类
/// </summary>
public class JobLogBLL
{ /// <summary>
/// 添加Job日志信息
/// </summary>
/// <param name="jobLog"></param>
/// <returns></returns>
public int AddLog(Job_Log jobLog)
{
int result = ; if (jobLog == null)
return result;
try
{
string SqlStr = string.Format("insert into job_log(job_name,job_result,job_exception,job_exetime,job_exedate,job_exestate) values('{0}','{1}','{2}',{3},'{4}',{5})",
jobLog.Job_name, jobLog.Job_result, jobLog.Job_exception, jobLog.Job_exetime, jobLog.Job_exedate.ToString("yyyy-MM-dd HH:mm:ss"), jobLog.Job_exestate);
result = MySqlHelper.ExceuteSql(SqlStr);
}
finally
{ } return result;
} /// <summary>
/// job日志列表
/// </summary>
/// <returns></returns>
public List<Job_Log> GetJobLogList()
{
List<Job_Log> list = null; try
{
string SqlStr = "select * from job_log";
var ds = MySqlHelper.GetDataSet(SqlStr);
if (ds != null && ds.Tables[].Rows.Count > )
{
list = new List<Job_Log>();
Job_Log info = new Job_Log();
foreach (System.Data.DataRow row in ds.Tables[].Rows)
{
info = Job_Log.ToEntity<Job_Log>(row, info);
if (info != null)
list.Add(info);
}
}
}
finally
{ } return list;
} /// <summary>
/// job日志列表
/// </summary>
/// <returns></returns>
public List<Job_Log> GetJobLogList(int pageIndex, int pageSize)
{
List<Job_Log> list = null; try
{
string SqlStr = "select * from job_log";
SqlStr += string.Format(" limit {0},{1};", (pageIndex - ) * pageSize, pageSize);
var ds = MySqlHelper.GetDataSet(SqlStr);
if (ds != null && ds.Tables[].Rows.Count > )
{
list = new List<Job_Log>();
Job_Log info = new Job_Log();
foreach (System.Data.DataRow row in ds.Tables[].Rows)
{
info = Job_Log.ToEntity<Job_Log>(row, info);
if (info != null)
list.Add(info);
}
}
}
finally
{ } return list;
} public int GetJobLogCount(int state = -)
{
int count = ; try
{
string SqlStr = "select count(0) from job_log";
if (state > -)
{
SqlStr += " where job_exestate=" + state;
}
var ds = MySqlHelper.GetReader(SqlStr);
if (ds != null)
{
int.TryParse(ds.ToString(), out count);
}
}
finally
{ } return count;
} }
这些都是数据库的基本操作,我就直接贴出来了。为了规范,我们就定了一个接口,供所有Job任务来实际业务,接口很简单,具体如下:
/// <summary>
/// 基Job
/// </summary>
public interface IJob
{
/// <summary>
/// 执行任务
/// </summary>
bool Exceute();
}
好了,下面我们就开始我们的Job托管器-Window Server。为了方便,我就使用Topshelf,因为创建JobManage.Service这个项目时,一定要选择Console项目(我一开始就直接使用了Service项目,然后一直运行不起来)。
那现在来创建一个JobServer类,实现ServiceControl, ServiceSuspend 两大接口的方法,在服务启动的时候,实例化Schedule,然后加入检查Job的Job任务,定期增加或删除Schedule里的Job。
实现如下:
public bool Start(HostControl hostControl)
{
if (JobConfig.factory == null)
{
JobConfig.factory = new StdSchedulerFactory();
JobConfig.scheduler = JobConfig.factory.GetScheduler();
JobConfig.scheduler.Start(); //创建循环Job
IJobDetail job = JobBuilder.Create<LoopJob>().WithIdentity("LoopJob", "group1").Build();
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("LoopJobtrigger", "group1")
.WithCronSchedule("0 0/5 * * * ?") //30分种执行一次
.StartAt(new DateTimeOffset(DateTime.Now.AddSeconds()))
.Build(); JobConfig.scheduler.ScheduleJob(job, trigger);
}
else
{
JobConfig.scheduler.Start();
}
return true;
} public bool Stop(HostControl hostControl)
{
if (JobConfig.factory != null)
{
JobConfig.scheduler.Shutdown(false);
JobConfig.factory = null;
JobConfig.scheduler = null;
}
return true;
}
好了,这一节就先到这,下面的我喝杯茶再来~
源码github:https://github.com/zshankang/JobManage
如果有其他的问题,可以加QQ群:1600800