C#定时任务(Timer)
2024-09-08 16:07:22
新建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();
} }
}
最新文章
- SQL Server 2012 The report server cannot open a connection to the report server database
- Html登录表单阻止自动填充
- java的重写规则
- linux下重启tomcat,日志查看
- Technical analysis of client identification mechanisms
- WebForm上传文件FileUpload
- tomcat服务器配置多个项目
- Live555研究之三 RTSP Server处理请求
- 《精通CSS:高级Web标准解决方案》学习笔记(上)
- 如何快速方便的输出向量vector容器中不重复的内容
- SCOPE_IDENTITY()
- 线上Django项目python2到3升级日记
- expdp/impdp数据泵用法
- 【Java】浅谈Java IO
- report源码分析——report_handle和report_server和report_catcher
- Ubuntu下搭建Hyperledger Fabric v1.0环境
- JDBC 查询的三大参数
- Spark Storage(一) 集群下的区块管理
- AE IRasterCursor 获取栅格图层像素值
- CPU硬件辅助虚拟化技术