C#定时任务(Timer)

新建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();
        }
       
    }
}
 
posted @ 2020-07-02 15:16  艺洁  阅读(1115)  评论(0编辑  收藏  举报