首先的一个需求是在OA系统中定时跑一些定时作业,例如发放年假等事务,之前的做法是在服务器上加入一个服务,用系统定时作业去跑服务,这样有个问题就是当系统在发布的过程中,有可能忘记启动服务而导致无法定时执行。
在网上查了一下资料,这样的需求一般在全局application上做一定时器,定时执行任务。
MVC架构中Global.asax是指定路由的文件,而在里面定义了事件Application_Start和Application_End事件,这样可以在发布过后,直接启用定时器。
using System.Net;
using System.Threading;
using System.IO;
using System.Timers;
using System.Configuration;
using TajimaOA.UI.Common;
using TajimaOA.UI.OA;
//2014-03-14 add by WesChen 声明系统定时器
System.Timers.Timer MC_timer;
protected void Application_Start()
{
//系统是否允许计时器运行
string l_SystemAllowTimer = System.Web.Configuration.WebConfigurationManager.AppSettings["TajimaAllowWorkTimer"];
if (l_SystemAllowTimer == "Y")
{
//计时器运行间隔时间
int l_TimerInterval = Convert.ToInt32(System.Web.Configuration.WebConfigurationManager.AppSettings["TajimaAllowTimerInterval"]);
MC_timer = new System.Timers.Timer(l_TimerInterval);
MC_timer.Elapsed += new ElapsedEventHandler(SystemExeTimerConsole);
MC_timer.Start();
}
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
///-------------------------------------------------
protected void Application_End()
{
EndSystemTimer();
//定时器运行地址,方便IIS重启时可以恢复作业运行
string url = System.Web.Configuration.WebConfigurationManager.AppSettings["TajimaTimerRunPath"];
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
Stream receiveStream = myHttpWebResponse.GetResponseStream();//得到回写的字节流
}
///-------------------------------------------------
private static void SystemExeTimerConsole(object sender, System.Timers.ElapsedEventArgs e)
{
TajimaOA.UI.Controllers.SystemManagerController l_SystemManagerController = new Controllers.SystemManagerController();
l_SystemManagerController.SystemRunTimer(System.DateTime.Now);
//该方法为作业池的入口,传入当前调用时间,调用在这个时间段需要执行的作业,作业运行过后,再计算下次调用时间,如此反复
}
///-------------------------------------------------
private static void EndSystemTimer()
{
TajimaOA.UI.Controllers.SystemManagerController l_SystemManagerController = new Controllers.SystemManagerController();
l_SystemManagerController.EndSystemTimer();
}
//****************************************************************************
#region 2014-03-14 add by WesChen 系统作业池功能
private static string MC_SystemTimerCode = "TajimaTimer";//固定编号
/// <summary>
/// 2014-03-14 add by WesChen
/// 计时器运行作业池
/// </summary>
/// <param name="pi_RunTime">系统运行时间</param>
public void SystemRunTimer(DateTime pi_RunTime)
{
try
{
//运行作业池
SystemJobRuning(pi_RunTime);
//计定时器运行状态
StartSystemTimer(pi_RunTime);
}
catch (Exception)
{
EndSystemTimer();
}
}
public JsonResult SystemRunTimer()
{
JsonResultBase result = new JsonResultBase();
result.success = true;
try
{
StartSystemTimer(System.DateTime.Now);
}
catch (Exception)
{
result.success = false;
}
return Json(result, JsonRequestBehavior.AllowGet);
}
/// <summary>
/// 2014-03-14 add by WesChen
/// 运行定时器
/// </summary>
/// <param name="pi_StartTime"></param>
public void StartSystemTimer(DateTime pi_StartTime)
{
SystemManageServiceClient l_ServiceClient=new SystemManageServiceClient();
SystemTimerSettingEntity l_data = http://www.mamicode.com/l_ServiceClient.GetSystemTimerSettingByCode(MC_SystemTimerCode);
//正在运行
l_data.IsRuning = "Y";
//最后运行时间
l_data.LastRuningDateTime = pi_StartTime;
//保存
l_ServiceClient.UpdateSystemTimerSetting(l_data);
}
/// <summary>
/// 2014-03-14 add by WesChen
/// 结束定时器
/// </summary>
/// <param name="pi_EndTime"></param>
public void EndSystemTimer()
{
SystemManageServiceClient l_ServiceClient = new SystemManageServiceClient();
SystemTimerSettingEntity l_data = http://www.mamicode.com/l_ServiceClient.GetSystemTimerSettingByCode(MC_SystemTimerCode);
//正在运行
l_data.IsRuning = "N";
//保存
l_ServiceClient.UpdateSystemTimerSetting(l_data);
}
/// <summary>
/// 2014-03-19 add by WesChen
/// 获取系统定时器状态
/// </summary>
/// <returns></returns>
public JsonResult GetSystemTimerState()
{
SystemManageServiceClient l_ServiceClient = new SystemManageServiceClient();
SystemTimerSettingEntity l_data = http://www.mamicode.com/l_ServiceClient.GetSystemTimerSettingByCode(MC_SystemTimerCode);
return Json(l_data, JsonRequestBehavior.AllowGet);
}
#endregion
//*************************************************************************************
public void SystemJobRuning(DateTime pi_JobDateTime)
{
SystemManageServiceClient serviceClient = new SystemManageServiceClient();
//iDisplayLength,iDisplayStart,sEcho,iTotalDisplayRecords
SearchParamEntity searchParam = new SearchParamEntity();
int totalCount = 0;
int currentPage = 1;
int pageSize = 999999;
SystemJobSettingEntity[] l_SystemJobSettingList = serviceClient.GetSystemJobSettingList(out totalCount, searchParam, currentPage, pageSize);
for (int i = 0; i < l_SystemJobSettingList.Length; i++)
{
//有效
if (l_SystemJobSettingList[i].IsWork.ToUpper() == "Y")
{
if (l_SystemJobSettingList[i].NextWorkTime.Value.Date == pi_JobDateTime.Date && l_SystemJobSettingList[i].NextWorkTime.Value.Hour == pi_JobDateTime.Hour && l_SystemJobSettingList[i].NextWorkTime.Value.Minute == pi_JobDateTime.Minute)
{
try
{
string url = l_SystemJobSettingList[i].JobRunUrl;
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
Stream receiveStream = myHttpWebResponse.GetResponseStream();//得到回写的字节流
UpdateSystemJobSettingNextWorkTime(new Guid(l_SystemJobSettingList[i].ID.ToString()));
OA.SystemManageService.SystemOperateLogEntity data = http://www.mamicode.com/new OA.SystemManageService.SystemOperateLogEntity();
data.ID = Guid.NewGuid();
data.OperateType = "SystemJobRunLog";
data.OperateDesc = "Tajima作业操作-" + l_SystemJobSettingList[i].JobName;
data.OperatorUserID = new Guid("00000000-0000-0000-0000-000000000000");
data.Remark = "系统作业-" + l_SystemJobSettingList[i].JobName + "在" + pi_JobDateTime.ToString("yyyy-MM-dd HH:mm:ss") + "运行成功。";
OA.SystemManageService.SystemManageServiceClient systemManageServiceClient = new OA.SystemManageService.SystemManageServiceClient();
systemManageServiceClient.AddOperateLog(data);
}
catch (Exception)
{
OA.SystemManageService.SystemOperateLogEntity data = http://www.mamicode.com/new OA.SystemManageService.SystemOperateLogEntity();
data.ID = Guid.NewGuid();
data.OperateType = "SystemJobRunError";
data.OperateDesc = "Tajima作业操作-" + l_SystemJobSettingList[i].JobName;
data.OperatorUserID = new Guid("00000000-0000-0000-0000-000000000000");
data.Remark = "系统作业-" + l_SystemJobSettingList[i].JobName + "在" + pi_JobDateTime.ToString("yyyy-MM-dd HH:mm:ss") + "运行未能成功。";
OA.SystemManageService.SystemManageServiceClient systemManageServiceClient = new OA.SystemManageService.SystemManageServiceClient();
systemManageServiceClient.AddOperateLog(data);
}
}
}
}
}
//***********************************************************************************
public void UpdateSystemJobSettingNextWorkTime(Guid id)
{
OA.SystemManageService.SystemManageServiceClient l_SystemManageService = new OA.SystemManageService.SystemManageServiceClient();
SystemJobSettingEntity l_data = http://www.mamicode.com/l_SystemManageService.GetSystemJobSettingByID(id);
if (l_data.IntervalType.ToUpper() == "ONCE")
{
#region 全局运行一次
l_data.IsWork = "N";
l_data.LoseEfficacyDateTime = System.DateTime.Now;
//修改作业
l_SystemManageService.UpdateSystemJobSetting(l_data);
#endregion
}
else if (l_data.IntervalType.ToUpper() == "REPEAT")
{
#region 多次运行
if (l_data.EndDate.Trim() == "")
{
#region 无结束日期
if (l_data.RunCount.ToUpper() == "ONLYONE")
{
#region 重复一次、下次为加一天
l_data.NextWorkTime = l_data.NextWorkTime.Value.AddDays(1);
l_SystemManageService.UpdateSystemJobSetting(l_data);
#endregion
}
else if (l_data.RunCount.ToUpper() == "RUNMANY")
{
if (l_data.RunIntervalUnit.ToUpper() == "HOUR")
{
if (l_data.NextWorkTime.Value.AddHours(Convert.ToInt32(l_data.RunIntervalCount)).TimeOfDay > Convert.ToDateTime(l_data.EndTime).TimeOfDay)
{
l_data.NextWorkTime = new DateTime(Convert.ToDateTime(l_data.NextWorkTime).Year, Convert.ToDateTime(l_data.NextWorkTime).Month, Convert.ToDateTime(l_data.NextWorkTime).Day, Convert.ToDateTime(l_data.StartTime).Hour, Convert.ToDateTime(l_data.StartTime).Minute, 0).AddDays(1);
l_SystemManageService.UpdateSystemJobSetting(l_data);
}
else
{
l_data.NextWorkTime = l_data.NextWorkTime.Value.AddHours(Convert.ToInt32(l_data.RunIntervalCount));
l_SystemManageService.UpdateSystemJobSetting(l_data);
}
}
else
{
if (l_data.NextWorkTime.Value.AddMinutes(Convert.ToInt32(l_data.RunIntervalCount)).TimeOfDay > Convert.ToDateTime(l_data.EndTime).TimeOfDay)
{
l_data.NextWorkTime = new DateTime(Convert.ToDateTime(l_data.NextWorkTime).Year, Convert.ToDateTime(l_data.NextWorkTime).Month, Convert.ToDateTime(l_data.NextWorkTime).Day, Convert.ToDateTime(l_data.StartTime).Hour, Convert.ToDateTime(l_data.StartTime).Minute, 0).AddDays(1);
l_SystemManageService.UpdateSystemJobSetting(l_data);
}
else
{
l_data.NextWorkTime = l_data.NextWorkTime.Value.AddMinutes(Convert.ToInt32(l_data.RunIntervalCount));
l_SystemManageService.UpdateSystemJobSetting(l_data);
}
}
}
#endregion
}
else
{
#region 指定结束日期
if (Convert.ToDateTime(l_data.EndDate).Date > System.DateTime.Now.Date)
{
#region 未到最后日期
if (l_data.RunCount.ToUpper() == "ONLYONE")
{
#region 重复一次、下次为加一天
l_data.NextWorkTime = l_data.NextWorkTime.Value.AddDays(1);
l_SystemManageService.UpdateSystemJobSetting(l_data);
#endregion
}
else if (l_data.RunCount.ToUpper() == "RUNMANY")
{
#region 多次
if (l_data.RunIntervalUnit.ToUpper() == "HOUR")
{
if (l_data.NextWorkTime.Value.AddHours(Convert.ToInt32(l_data.RunIntervalCount)).TimeOfDay > Convert.ToDateTime(l_data.EndTime).TimeOfDay)
{
l_data.NextWorkTime = new DateTime(Convert.ToDateTime(l_data.NextWorkTime).Year, Convert.ToDateTime(l_data.NextWorkTime).Month, Convert.ToDateTime(l_data.NextWorkTime).Day, Convert.ToDateTime(l_data.StartTime).Hour, Convert.ToDateTime(l_data.StartTime).Minute, 0).AddDays(1);
l_SystemManageService.UpdateSystemJobSetting(l_data);
}
else
{
l_data.NextWorkTime = l_data.NextWorkTime.Value.AddHours(Convert.ToInt32(l_data.RunIntervalCount));
l_SystemManageService.UpdateSystemJobSetting(l_data);
}
}
else
{
if (l_data.NextWorkTime.Value.AddMinutes(Convert.ToInt32(l_data.RunIntervalCount)).TimeOfDay > Convert.ToDateTime(l_data.EndTime).TimeOfDay)
{
l_data.NextWorkTime = new DateTime(Convert.ToDateTime(l_data.NextWorkTime).Year, Convert.ToDateTime(l_data.NextWorkTime).Month, Convert.ToDateTime(l_data.NextWorkTime).Day, Convert.ToDateTime(l_data.StartTime).Hour, Convert.ToDateTime(l_data.StartTime).Minute, 0).AddDays(1);
l_SystemManageService.UpdateSystemJobSetting(l_data);
}
else
{
l_data.NextWorkTime = l_data.NextWorkTime.Value.AddMinutes(Convert.ToInt32(l_data.RunIntervalCount));
l_SystemManageService.UpdateSystemJobSetting(l_data);
}
}
#endregion
}
#endregion
}
if (Convert.ToDateTime(l_data.EndDate).Date == System.DateTime.Now.Date)
{
#region 等于最后日期
if (Convert.ToDateTime(l_data.EndTime).TimeOfDay > System.DateTime.Now.TimeOfDay)
{
#region 当前时间小于最后运行时间
if (l_data.RunCount.ToUpper() == "ONLYONE")
{
#region 重复一次、下次为加一天
l_data.NextWorkTime = l_data.NextWorkTime.Value.AddDays(1);
l_SystemManageService.UpdateSystemJobSetting(l_data);
#endregion
}
else if (l_data.RunCount.ToUpper() == "RUNMANY")
{
#region 多次
if (l_data.RunIntervalUnit.ToUpper() == "HOUR")
{
if (l_data.NextWorkTime.Value.AddHours(Convert.ToInt32(l_data.RunIntervalCount)).TimeOfDay > Convert.ToDateTime(l_data.EndTime).TimeOfDay)
{
l_data.NextWorkTime = new DateTime(Convert.ToDateTime(l_data.NextWorkTime).Year, Convert.ToDateTime(l_data.NextWorkTime).Month, Convert.ToDateTime(l_data.NextWorkTime).Day, Convert.ToDateTime(l_data.StartTime).Hour, Convert.ToDateTime(l_data.StartTime).Minute, 0).AddDays(1);
l_SystemManageService.UpdateSystemJobSetting(l_data);
}
else
{
l_data.NextWorkTime = l_data.NextWorkTime.Value.AddHours(Convert.ToInt32(l_data.RunIntervalCount));
l_SystemManageService.UpdateSystemJobSetting(l_data);
}
}
else
{
if (l_data.NextWorkTime.Value.AddMinutes(Convert.ToInt32(l_data.RunIntervalCount)).TimeOfDay > Convert.ToDateTime(l_data.EndTime).TimeOfDay)
{
l_data.NextWorkTime = new DateTime(Convert.ToDateTime(l_data.NextWorkTime).Year, Convert.ToDateTime(l_data.NextWorkTime).Month, Convert.ToDateTime(l_data.NextWorkTime).Day, Convert.ToDateTime(l_data.StartTime).Hour, Convert.ToDateTime(l_data.StartTime).Minute, 0).AddDays(1);
l_SystemManageService.UpdateSystemJobSetting(l_data);
}
else
{
l_data.NextWorkTime = l_data.NextWorkTime.Value.AddMinutes(Convert.ToInt32(l_data.RunIntervalCount));
l_SystemManageService.UpdateSystemJobSetting(l_data);
}
}
#endregion
}
#endregion
}
else
{
#region 日期相等、时间大于或等于最后运行时间
l_data.IsWork = "N";
l_SystemManageService.UpdateSystemJobSetting(l_data);
#endregion
}
#endregion
}
else
{
#region 超过最后日期
l_data.IsWork = "N";
l_SystemManageService.UpdateSystemJobSetting(l_data);
#endregion
}
#endregion
}
#endregion
}
}
.net MVC全局定时器执行作业