C#定时任务(Timer)

2023-03-14,

新建Timer

using BaseAsset.Data.Infrastructure;
using BaseAsset.Data.Repositories;
using BaseAsset.Entities;
using BaseAsset.Services;
using BaseAsset.Services.Abstract;
using System;
using System.Threading;
using System.Timers; namespace BaseAsset.Api.Timer
{
public class CostanalysisTimer
{
private static int inTimer = 0;
public void SetTimer()
{
System.Timers.Timer aTimer = new System.Timers.Timer(); aTimer.Elapsed += new ElapsedEventHandler(OnTimer);
//aTimer.Interval = 60000;
aTimer.Interval = 10800000;
aTimer.Enabled = true;
}
public void OnTimer(Object source, ElapsedEventArgs e)
{
try
{
//防止重入问题
if (Interlocked.Exchange(ref inTimer, 1) == 0)
{
IFoodService _foodService = new FoodService(
new EntityBaseRepository<fd_purchase>(),
new EntityBaseRepository<fd_purchase_detail>(),
new EntityBaseRepository<fd_cost_analysis>(),
new EntityBaseRepository<fd_cost_analysis_detail>(), new UnitOfWork());//工作单元实例化(工作单元的接入,保证了数据上下文在一个操作单元中只有一个,它可以通过构造方法注入到其它类中,实现跨类进行方法的组合。)
_foodService.Addcostanalysis();
Interlocked.Exchange(ref inTimer, 0);
}
}
catch (Exception ex)
{
Interlocked.Exchange(ref inTimer, 0);
throw (ex);
} }
}
}
Global.asax
using BaseAsset.Api.Mappings;
using BaseAsset.Api.Timer;
using System.Web.Http; namespace BaseAsset.Api
{
public class WebApiApplication : System.Web.HttpApplication
{ protected void Application_Start()
{
CostanalysisTimer time = new CostanalysisTimer();
time.SetTimer();
} }
}
 

C#定时任务(Timer)的相关教程结束。

《C#定时任务(Timer).doc》

下载本文的Word格式文档,以方便收藏与打印。